LCOV - code coverage report
Current view: top level - lib/Support - raw_ostream.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 291 321 90.7 %
Date: 2018-02-21 06:32:55 Functions: 48 55 87.3 %
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    87508396 : 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    43754198 :   if (BufferMode == InternalBuffer)
      78     5650390 :     delete [] OutBufStart;
      79    43754198 : }
      80             : 
      81             : // An out of line virtual method to provide a home for the class vtable.
      82           0 : void raw_ostream::handle() {}
      83             : 
      84     5414808 : size_t raw_ostream::preferred_buffer_size() const {
      85             :   // BUFSIZ is intended to be a reasonable default.
      86     5414808 :   return BUFSIZ;
      87             : }
      88             : 
      89     5449628 : void raw_ostream::SetBuffered() {
      90             :   // Ask the subclass to determine an appropriate buffer size.
      91     5449628 :   if (size_t Size = preferred_buffer_size())
      92     5449628 :     SetBufferSize(Size);
      93             :   else
      94             :     // It may return 0, meaning this stream should be unbuffered.
      95           0 :     SetUnbuffered();
      96     5449628 : }
      97             : 
      98    43593535 : 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    43593535 :   if (BufferMode == InternalBuffer)
     108    43526082 :     delete [] OutBufStart;
     109    43593535 :   OutBufStart = BufferStart;
     110    43593535 :   OutBufEnd = OutBufStart+Size;
     111    43593535 :   OutBufCur = OutBufStart;
     112    43593535 :   BufferMode = Mode;
     113             : 
     114             :   assert(OutBufStart <= OutBufEnd && "Invalid size!");
     115    43593535 : }
     116             : 
     117    34189621 : raw_ostream &raw_ostream::operator<<(unsigned long N) {
     118    34189621 :   write_integer(*this, static_cast<uint64_t>(N), 0, IntegerStyle::Integer);
     119    34189622 :   return *this;
     120             : }
     121             : 
     122     8303413 : raw_ostream &raw_ostream::operator<<(long N) {
     123     8303413 :   write_integer(*this, static_cast<int64_t>(N), 0, IntegerStyle::Integer);
     124     8303415 :   return *this;
     125             : }
     126             : 
     127           5 : raw_ostream &raw_ostream::operator<<(unsigned long long N) {
     128           5 :   write_integer(*this, static_cast<uint64_t>(N), 0, IntegerStyle::Integer);
     129           5 :   return *this;
     130             : }
     131             : 
     132       18410 : raw_ostream &raw_ostream::operator<<(long long N) {
     133       18410 :   write_integer(*this, static_cast<int64_t>(N), 0, IntegerStyle::Integer);
     134       18410 :   return *this;
     135             : }
     136             : 
     137      383108 : raw_ostream &raw_ostream::write_hex(unsigned long long N) {
     138      383108 :   llvm::write_hex(*this, N, HexPrintStyle::Lower);
     139      383108 :   return *this;
     140             : }
     141             : 
     142          37 : raw_ostream &raw_ostream::write_uuid(const uuid_t UUID) {
     143        1221 :   for (int Idx = 0; Idx < 16; ++Idx) {
     144        1184 :     *this << format("%02" PRIX32, UUID[Idx]);
     145         592 :     if (Idx == 3 || Idx == 5 || Idx == 7 || Idx == 9)
     146         148 :       *this << "-";
     147             :   }
     148          37 :   return *this;
     149             : }
     150             : 
     151             : 
     152      163782 : raw_ostream &raw_ostream::write_escaped(StringRef Str,
     153             :                                         bool UseHexEscapes) {
     154     2346868 :   for (unsigned char c : Str) {
     155     1091543 :     switch (c) {
     156             :     case '\\':
     157             :       *this << '\\' << '\\';
     158             :       break;
     159             :     case '\t':
     160             :       *this << '\\' << 't';
     161             :       break;
     162             :     case '\n':
     163             :       *this << '\\' << 'n';
     164             :       break;
     165             :     case '"':
     166             :       *this << '\\' << '"';
     167             :       break;
     168     1090423 :     default:
     169     1090423 :       if (std::isprint(c)) {
     170             :         *this << c;
     171             :         break;
     172             :       }
     173             : 
     174             :       // Write out the escaped representation.
     175       15816 :       if (UseHexEscapes) {
     176             :         *this << '\\' << 'x';
     177         164 :         *this << hexdigit((c >> 4 & 0xF));
     178         164 :         *this << hexdigit((c >> 0) & 0xF);
     179             :       } else {
     180             :         // Always use a full 3-character octal escape.
     181             :         *this << '\\';
     182       15652 :         *this << char('0' + ((c >> 6) & 7));
     183       15652 :         *this << char('0' + ((c >> 3) & 7));
     184       15652 :         *this << char('0' + ((c >> 0) & 7));
     185             :       }
     186             :     }
     187             :   }
     188             : 
     189      163782 :   return *this;
     190             : }
     191             : 
     192       15245 : raw_ostream &raw_ostream::operator<<(const void *P) {
     193       15245 :   llvm::write_hex(*this, (uintptr_t)P, HexPrintStyle::PrefixLower);
     194       15245 :   return *this;
     195             : }
     196             : 
     197       29229 : raw_ostream &raw_ostream::operator<<(double N) {
     198       29229 :   llvm::write_double(*this, N, FloatStyle::Exponent);
     199       29229 :   return *this;
     200             : }
     201             : 
     202     5834278 : void raw_ostream::flush_nonempty() {
     203             :   assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty.");
     204     5834278 :   size_t Length = OutBufCur - OutBufStart;
     205     5834278 :   OutBufCur = OutBufStart;
     206     5834278 :   write_impl(OutBufStart, Length);
     207     5834277 : }
     208             : 
     209   109582886 : raw_ostream &raw_ostream::write(unsigned char C) {
     210             :   // Group exceptional cases into a single branch.
     211   109582886 :   if (LLVM_UNLIKELY(OutBufCur >= OutBufEnd)) {
     212   107103303 :     if (LLVM_UNLIKELY(!OutBufStart)) {
     213   107074687 :       if (BufferMode == Unbuffered) {
     214   104608270 :         write_impl(reinterpret_cast<char*>(&C), 1);
     215   104608269 :         return *this;
     216             :       }
     217             :       // Set up a buffer and start over.
     218     2466417 :       SetBuffered();
     219     2466417 :       return write(C);
     220             :     }
     221             : 
     222       28616 :     flush_nonempty();
     223             :   }
     224             : 
     225     2508200 :   *OutBufCur++ = C;
     226     2508200 :   return *this;
     227             : }
     228             : 
     229   349078830 : raw_ostream &raw_ostream::write(const char *Ptr, size_t Size) {
     230             :   // Group exceptional cases into a single branch.
     231   352515041 :   if (LLVM_UNLIKELY(size_t(OutBufEnd - OutBufCur) < Size)) {
     232   268248144 :     if (LLVM_UNLIKELY(!OutBufStart)) {
     233   267787345 :       if (BufferMode == Unbuffered) {
     234   264804136 :         write_impl(Ptr, Size);
     235   264804950 :         return *this;
     236             :       }
     237             :       // Set up a buffer and start over.
     238     2983209 :       SetBuffered();
     239     2983211 :       return write(Ptr, Size);
     240             :     }
     241             : 
     242             :     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      460799 :     if (LLVM_UNLIKELY(OutBufCur == OutBufStart)) {
     248             :       assert(NumBytes != 0 && "undefined behavior");
     249        7799 :       size_t BytesToWrite = Size - (Size % NumBytes);
     250        7799 :       write_impl(Ptr, BytesToWrite);
     251             :       size_t BytesRemaining = Size - BytesToWrite;
     252        7799 :       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        7799 :       copy_to_buffer(Ptr + BytesToWrite, BytesRemaining);
     257        7799 :       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      453000 :     copy_to_buffer(Ptr, NumBytes);
     263      453000 :     flush_nonempty();
     264      453000 :     return write(Ptr + NumBytes, Size - NumBytes);
     265             :   }
     266             : 
     267    84266897 :   copy_to_buffer(Ptr, Size);
     268             : 
     269    84266908 :   return *this;
     270             : }
     271             : 
     272    84727693 : 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    84727693 :   switch (Size) {
     278     8427996 :   case 4: OutBufCur[3] = Ptr[3]; LLVM_FALLTHROUGH;
     279     9782461 :   case 3: OutBufCur[2] = Ptr[2]; LLVM_FALLTHROUGH;
     280    49923055 :   case 2: OutBufCur[1] = Ptr[1]; LLVM_FALLTHROUGH;
     281    64870179 :   case 1: OutBufCur[0] = Ptr[0]; LLVM_FALLTHROUGH;
     282             :   case 0: break;
     283    19195623 :   default:
     284    19195623 :     memcpy(OutBufCur, Ptr, Size);
     285    19195623 :     break;
     286             :   }
     287             : 
     288    84727693 :   OutBufCur += Size;
     289    84727693 : }
     290             : 
     291             : // Formatted output.
     292     4200878 : 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             :   size_t NextBufferSize = 127;
     296     4200878 :   size_t BufferBytesLeft = OutBufEnd - OutBufCur;
     297     4200878 :   if (BufferBytesLeft > 3) {
     298     3394150 :     size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft);
     299             : 
     300             :     // Common case is that we have plenty of space.
     301     1697075 :     if (BytesUsed <= BufferBytesLeft) {
     302     1696250 :       OutBufCur += BytesUsed;
     303     1696250 :       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     2504693 :     V.resize(NextBufferSize);
     318             : 
     319             :     // Try formatting into the SmallVector.
     320     5009386 :     size_t BytesUsed = Fmt.print(V.data(), NextBufferSize);
     321             : 
     322             :     // If BytesUsed fit into the vector, we win.
     323     2504693 :     if (BytesUsed <= NextBufferSize)
     324     2504628 :       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       13485 : raw_ostream &raw_ostream::operator<<(const formatv_object_base &Obj) {
     333             :   SmallString<128> S;
     334       13485 :   Obj.format(*this);
     335       13485 :   return *this;
     336             : }
     337             : 
     338        3417 : raw_ostream &raw_ostream::operator<<(const FormattedString &FS) {
     339        3417 :   if (FS.Str.size() >= FS.Width || FS.Justify == FormattedString::JustifyNone) {
     340         123 :     this->operator<<(FS.Str);
     341         123 :     return *this;
     342             :   }
     343        3294 :   const size_t Difference = FS.Width - FS.Str.size();
     344        3294 :   switch (FS.Justify) {
     345         976 :   case FormattedString::JustifyLeft:
     346         976 :     this->operator<<(FS.Str);
     347         976 :     this->indent(Difference);
     348         976 :     break;
     349        2315 :   case FormattedString::JustifyRight:
     350        2315 :     this->indent(Difference);
     351        2315 :     this->operator<<(FS.Str);
     352        2315 :     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     8941064 : raw_ostream &raw_ostream::operator<<(const FormattedNumber &FN) {
     367     8941064 :   if (FN.Hex) {
     368             :     HexPrintStyle Style;
     369      630475 :     if (FN.Upper && FN.HexPrefix)
     370             :       Style = HexPrintStyle::PrefixUpper;
     371      628573 :     else if (FN.Upper && !FN.HexPrefix)
     372             :       Style = HexPrintStyle::Upper;
     373        3759 :     else if (!FN.Upper && FN.HexPrefix)
     374             :       Style = HexPrintStyle::PrefixLower;
     375             :     else
     376             :       Style = HexPrintStyle::Lower;
     377     1260950 :     llvm::write_hex(*this, FN.HexValue, Style, FN.Width);
     378             :   } else {
     379             :     llvm::SmallString<16> Buffer;
     380             :     llvm::raw_svector_ostream Stream(Buffer);
     381     8310589 :     llvm::write_integer(Stream, FN.DecValue, 0, IntegerStyle::Integer);
     382     8310589 :     if (Buffer.size() < FN.Width)
     383     3178940 :       indent(FN.Width - Buffer.size());
     384             :     (*this) << Buffer;
     385             :   }
     386     8941064 :   return *this;
     387             : }
     388             : 
     389        3992 : raw_ostream &raw_ostream::operator<<(const FormattedBytes &FB) {
     390        3992 :   if (FB.Bytes.empty())
     391             :     return *this;
     392             : 
     393             :   size_t LineIndex = 0;
     394        3937 :   auto Bytes = FB.Bytes;
     395             :   const size_t Size = Bytes.size();
     396        3937 :   HexPrintStyle HPS = FB.Upper ? HexPrintStyle::Upper : HexPrintStyle::Lower;
     397             :   uint64_t OffsetWidth = 0;
     398        3937 :   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        1841 :     size_t Lines = Size / FB.NumPerLine;
     403        1841 :     uint64_t MaxOffset = *FB.FirstByteOffset + Lines * FB.NumPerLine;
     404             :     unsigned Power = 0;
     405        1841 :     if (MaxOffset > 0)
     406             :       Power = llvm::Log2_64_Ceil(MaxOffset);
     407        5523 :     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        7874 :       alignTo(FB.NumPerLine, FB.ByteGroupSize) / FB.ByteGroupSize;
     413        3937 :   unsigned BlockCharWidth = FB.NumPerLine * 2 + NumByteGroups - 1;
     414             : 
     415     1699057 :   while (!Bytes.empty()) {
     416     1695120 :     indent(FB.IndentLevel);
     417             : 
     418     1695120 :     if (FB.FirstByteOffset.hasValue()) {
     419     1693002 :       uint64_t Offset = FB.FirstByteOffset.getValue();
     420     1693002 :       llvm::write_hex(*this, Offset + LineIndex, HPS, OffsetWidth);
     421     1693002 :       *this << ": ";
     422             :     }
     423             : 
     424     1695120 :     auto Line = Bytes.take_front(FB.NumPerLine);
     425             : 
     426             :     size_t CharsPrinted = 0;
     427             :     // Print the hex bytes for this line in groups
     428    55924464 :     for (size_t I = 0; I < Line.size(); ++I, CharsPrinted += 2) {
     429    27114672 :       if (I && (I % FB.ByteGroupSize) == 0) {
     430     5100639 :         ++CharsPrinted;
     431     5100639 :         *this << " ";
     432             :       }
     433    27114672 :       llvm::write_hex(*this, Line[I], HPS, 2);
     434             :     }
     435             : 
     436     1695120 :     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     1693004 :       indent(BlockCharWidth - CharsPrinted + 2);
     441     1693004 :       *this << "|";
     442             : 
     443             :       // Print the ASCII char values for each byte on this line
     444    55877308 :       for (uint8_t Byte : Line) {
     445    27092152 :         if (isprint(Byte))
     446       28609 :           *this << static_cast<char>(Byte);
     447             :         else
     448             :           *this << '.';
     449             :       }
     450             :       *this << '|';
     451             :     }
     452             : 
     453             :     Bytes = Bytes.drop_front(Line.size());
     454     1695120 :     LineIndex += Line.size();
     455     1695120 :     if (LineIndex < Size)
     456             :       *this << '\n';
     457             :   }
     458             :   return *this;
     459             : }
     460             : 
     461             : /// indent - Insert 'NumSpaces' spaces.
     462    20912374 : 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    20912374 :   if (NumSpaces < array_lengthof(Spaces))
     469    20912374 :     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       62270 : 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             :   if (Filename == "-") {
     497       52986 :     EC = std::error_code();
     498             :     // If user requested binary then put stdout into binary mode if
     499             :     // possible.
     500       52986 :     if (!(Flags & sys::fs::F_Text))
     501       24395 :       sys::ChangeStdoutToBinary();
     502             :     return STDOUT_FILENO;
     503             :   }
     504             : 
     505             :   int FD;
     506        9284 :   EC = sys::fs::openFileForWrite(Filename, FD, Flags);
     507        9284 :   if (EC)
     508             :     return -1;
     509             : 
     510        8431 :   return FD;
     511             : }
     512             : 
     513       62270 : raw_fd_ostream::raw_fd_ostream(StringRef Filename, std::error_code &EC,
     514       62270 :                                sys::fs::OpenFlags Flags)
     515       62270 :     : 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      219114 : raw_fd_ostream::raw_fd_ostream(int fd, bool shouldClose, bool unbuffered)
     520      219114 :     : raw_pwrite_stream(unbuffered), FD(fd), ShouldClose(shouldClose) {
     521      219114 :   if (FD < 0 ) {
     522         853 :     ShouldClose = false;
     523         853 :     return;
     524             :   }
     525             : 
     526             :   // Do not attempt to close stdout or stderr. We used to try to maintain the
     527             :   // property that tools that support writing file to stdout should not also
     528             :   // write informational output to stdout, but in practice we were never able to
     529             :   // maintain this invariant. Many features have been added to LLVM and clang
     530             :   // (-fdump-record-layouts, optimization remarks, etc) that print to stdout, so
     531             :   // users must simply be aware that mixed output and remarks is a possibility.
     532      218261 :   if (FD <= STDERR_FILENO)
     533      199739 :     ShouldClose = false;
     534             : 
     535             :   // Get the starting position.
     536      218261 :   off_t loc = ::lseek(FD, 0, SEEK_CUR);
     537             : #ifdef LLVM_ON_WIN32
     538             :   // MSVCRT's _lseek(SEEK_CUR) doesn't return -1 for pipes.
     539             :   sys::fs::file_status Status;
     540             :   std::error_code EC = status(FD, Status);
     541             :   SupportsSeeking = !EC && Status.type() == sys::fs::file_type::regular_file;
     542             : #else
     543      218261 :   SupportsSeeking = loc != (off_t)-1;
     544             : #endif
     545      218261 :   if (!SupportsSeeking)
     546      193757 :     pos = 0;
     547             :   else
     548       24504 :     pos = static_cast<uint64_t>(loc);
     549             : }
     550             : 
     551      453901 : raw_fd_ostream::~raw_fd_ostream() {
     552      218822 :   if (FD >= 0) {
     553      216582 :     flush();
     554      216582 :     if (ShouldClose) {
     555       14720 :       if (auto EC = sys::Process::SafelyCloseFileDescriptor(FD))
     556             :         error_detected(EC);
     557             :     }
     558             :   }
     559             : 
     560             : #ifdef __MINGW32__
     561             :   // On mingw, global dtors should not call exit().
     562             :   // report_fatal_error() invokes exit(). We know report_fatal_error()
     563             :   // might not write messages to stderr when any errors were detected
     564             :   // on FD == 2.
     565             :   if (FD == 2) return;
     566             : #endif
     567             : 
     568             :   // If there are any pending errors, report them now. Clients wishing
     569             :   // to avoid report_fatal_error calls should check for errors with
     570             :   // has_error() and clear the error flag with clear_error() before
     571             :   // destructing raw_ostream objects which may have errors.
     572      218822 :   if (has_error())
     573          11 :     report_fatal_error("IO failure on output stream: " + error().message(),
     574             :                        /*GenCrashDiag=*/false);
     575      235079 : }
     576             : 
     577    19542357 : void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) {
     578             :   assert(FD >= 0 && "File already closed.");
     579    19542357 :   pos += Size;
     580             : 
     581             :   // The maximum write size is limited to SSIZE_MAX because a write
     582             :   // greater than SSIZE_MAX is implementation-defined in POSIX.
     583             :   // Since SSIZE_MAX is not portable, we use SIZE_MAX >> 1 instead.
     584             :   size_t MaxWriteSize = SIZE_MAX >> 1;
     585             : 
     586             : #if defined(__linux__)
     587             :   // It is observed that Linux returns EINVAL for a very large write (>2G).
     588             :   // Make it a reasonably small value.
     589    19542357 :   MaxWriteSize = 1024 * 1024 * 1024;
     590             : #elif defined(LLVM_ON_WIN32)
     591             :   // Writing a large size of output to Windows console returns ENOMEM. It seems
     592             :   // that, prior to Windows 8, WriteFile() is redirecting to WriteConsole(), and
     593             :   // the latter has a size limit (66000 bytes or less, depending on heap usage).
     594             :   if (::_isatty(FD) && !RunningWindows8OrGreater())
     595             :     MaxWriteSize = 32767;
     596             : #endif
     597             : 
     598             :   do {
     599    19542357 :     size_t ChunkSize = std::min(Size, MaxWriteSize);
     600    19542357 :     ssize_t ret = ::write(FD, Ptr, ChunkSize);
     601             : 
     602    19542357 :     if (ret < 0) {
     603             :       // If it's a recoverable error, swallow it and retry the write.
     604             :       //
     605             :       // Ideally we wouldn't ever see EAGAIN or EWOULDBLOCK here, since
     606             :       // raw_ostream isn't designed to do non-blocking I/O. However, some
     607             :       // programs, such as old versions of bjam, have mistakenly used
     608             :       // O_NONBLOCK. For compatibility, emulate blocking semantics by
     609             :       // spinning until the write succeeds. If you don't want spinning,
     610             :       // don't use O_NONBLOCK file descriptors with raw_ostream.
     611       16571 :       if (errno == EINTR || errno == EAGAIN
     612             : #ifdef EWOULDBLOCK
     613       16571 :           || errno == EWOULDBLOCK
     614             : #endif
     615             :           )
     616           0 :         continue;
     617             : 
     618             :       // Otherwise it's a non-recoverable error. Note it and quit.
     619       16571 :       error_detected(std::error_code(errno, std::generic_category()));
     620       16571 :       break;
     621             :     }
     622             : 
     623             :     // The write may have written some or all of the data. Update the
     624             :     // size and buffer pointer to reflect the remainder that needs
     625             :     // to be written. If there are no bytes left, we're done.
     626    19525786 :     Ptr += ret;
     627    19525786 :     Size -= ret;
     628    19525786 :   } while (Size > 0);
     629    19542357 : }
     630             : 
     631        1387 : void raw_fd_ostream::close() {
     632             :   assert(ShouldClose);
     633        1387 :   ShouldClose = false;
     634        1387 :   flush();
     635        1387 :   if (auto EC = sys::Process::SafelyCloseFileDescriptor(FD))
     636             :     error_detected(EC);
     637        1387 :   FD = -1;
     638        1387 : }
     639             : 
     640       17698 : uint64_t raw_fd_ostream::seek(uint64_t off) {
     641             :   assert(SupportsSeeking && "Stream does not support seeking!");
     642       17698 :   flush();
     643             : #ifdef LLVM_ON_WIN32
     644             :   pos = ::_lseeki64(FD, off, SEEK_SET);
     645             : #elif defined(HAVE_LSEEK64)
     646       17698 :   pos = ::lseek64(FD, off, SEEK_SET);
     647             : #else
     648             :   pos = ::lseek(FD, off, SEEK_SET);
     649             : #endif
     650       17697 :   if (pos == (uint64_t)-1)
     651           0 :     error_detected(std::error_code(errno, std::generic_category()));
     652       17697 :   return pos;
     653             : }
     654             : 
     655        8691 : void raw_fd_ostream::pwrite_impl(const char *Ptr, size_t Size,
     656             :                                  uint64_t Offset) {
     657        8691 :   uint64_t Pos = tell();
     658        8691 :   seek(Offset);
     659        8690 :   write(Ptr, Size);
     660        8691 :   seek(Pos);
     661        8691 : }
     662             : 
     663       70106 : size_t raw_fd_ostream::preferred_buffer_size() const {
     664             : #if !defined(_MSC_VER) && !defined(__MINGW32__) && !defined(__minix)
     665             :   // Windows and Minix have no st_blksize.
     666             :   assert(FD >= 0 && "File not yet open!");
     667             :   struct stat statbuf;
     668      140212 :   if (fstat(FD, &statbuf) != 0)
     669             :     return 0;
     670             : 
     671             :   // If this is a terminal, don't use buffering. Line buffering
     672             :   // would be a more traditional thing to do, but it's not worth
     673             :   // the complexity.
     674       70106 :   if (S_ISCHR(statbuf.st_mode) && isatty(FD))
     675             :     return 0;
     676             :   // Return the preferred block size.
     677       70106 :   return statbuf.st_blksize;
     678             : #else
     679             :   return raw_ostream::preferred_buffer_size();
     680             : #endif
     681             : }
     682             : 
     683         786 : raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold,
     684             :                                          bool bg) {
     685         786 :   if (sys::Process::ColorNeedsFlush())
     686           0 :     flush();
     687             :   const char *colorcode =
     688        1462 :     (colors == SAVEDCOLOR) ? sys::Process::OutputBold(bg)
     689         676 :     : sys::Process::OutputColor(colors, bold, bg);
     690         786 :   if (colorcode) {
     691         786 :     size_t len = strlen(colorcode);
     692         786 :     write(colorcode, len);
     693             :     // don't account colors towards output characters
     694         786 :     pos -= len;
     695             :   }
     696         786 :   return *this;
     697             : }
     698             : 
     699         779 : raw_ostream &raw_fd_ostream::resetColor() {
     700         779 :   if (sys::Process::ColorNeedsFlush())
     701           0 :     flush();
     702         779 :   const char *colorcode = sys::Process::ResetColor();
     703         779 :   if (colorcode) {
     704         779 :     size_t len = strlen(colorcode);
     705         779 :     write(colorcode, len);
     706             :     // don't account colors towards output characters
     707         779 :     pos -= len;
     708             :   }
     709         779 :   return *this;
     710             : }
     711             : 
     712           0 : raw_ostream &raw_fd_ostream::reverseColor() {
     713           0 :   if (sys::Process::ColorNeedsFlush())
     714           0 :     flush();
     715           0 :   const char *colorcode = sys::Process::OutputReverse();
     716           0 :   if (colorcode) {
     717           0 :     size_t len = strlen(colorcode);
     718           0 :     write(colorcode, len);
     719             :     // don't account colors towards output characters
     720           0 :     pos -= len;
     721             :   }
     722           0 :   return *this;
     723             : }
     724             : 
     725        1665 : bool raw_fd_ostream::is_displayed() const {
     726        1665 :   return sys::Process::FileDescriptorIsDisplayed(FD);
     727             : }
     728             : 
     729      190647 : bool raw_fd_ostream::has_colors() const {
     730      190647 :   return sys::Process::FileDescriptorHasColors(FD);
     731             : }
     732             : 
     733             : //===----------------------------------------------------------------------===//
     734             : //  outs(), errs(), nulls()
     735             : //===----------------------------------------------------------------------===//
     736             : 
     737             : /// outs() - This returns a reference to a raw_ostream for standard output.
     738             : /// Use it like: outs() << "foo" << "bar";
     739     1510874 : raw_ostream &llvm::outs() {
     740             :   // Set buffer settings to model stdout behavior.
     741             :   std::error_code EC;
     742     1519318 :   static raw_fd_ostream S("-", EC, sys::fs::F_None);
     743             :   assert(!EC);
     744     1510874 :   return S;
     745             : }
     746             : 
     747             : /// errs() - This returns a reference to a raw_ostream for standard error.
     748             : /// Use it like: errs() << "foo" << "bar";
     749      480040 : raw_ostream &llvm::errs() {
     750             :   // Set standard error to be unbuffered by default.
     751      480040 :   static raw_fd_ostream S(STDERR_FILENO, false, true);
     752      480040 :   return S;
     753             : }
     754             : 
     755             : /// nulls() - This returns a reference to a raw_ostream which discards output.
     756     8851739 : raw_ostream &llvm::nulls() {
     757     8853112 :   static raw_null_ostream S;
     758     8851739 :   return S;
     759             : }
     760             : 
     761             : //===----------------------------------------------------------------------===//
     762             : //  raw_string_ostream
     763             : //===----------------------------------------------------------------------===//
     764             : 
     765     4012019 : raw_string_ostream::~raw_string_ostream() {
     766     2006008 :   flush();
     767     2006011 : }
     768             : 
     769     1949811 : void raw_string_ostream::write_impl(const char *Ptr, size_t Size) {
     770     1949811 :   OS.append(Ptr, Size);
     771     1949811 : }
     772             : 
     773             : //===----------------------------------------------------------------------===//
     774             : //  raw_svector_ostream
     775             : //===----------------------------------------------------------------------===//
     776             : 
     777    19202172 : uint64_t raw_svector_ostream::current_pos() const { return OS.size(); }
     778             : 
     779   350197726 : void raw_svector_ostream::write_impl(const char *Ptr, size_t Size) {
     780   350197726 :   OS.append(Ptr, Ptr + Size);
     781   350198524 : }
     782             : 
     783        3509 : void raw_svector_ostream::pwrite_impl(const char *Ptr, size_t Size,
     784             :                                       uint64_t Offset) {
     785        3509 :   memcpy(OS.data() + Offset, Ptr, Size);
     786        3509 : }
     787             : 
     788             : //===----------------------------------------------------------------------===//
     789             : //  raw_null_ostream
     790             : //===----------------------------------------------------------------------===//
     791             : 
     792     1580290 : raw_null_ostream::~raw_null_ostream() {
     793             : #ifndef NDEBUG
     794             :   // ~raw_ostream asserts that the buffer is empty. This isn't necessary
     795             :   // with raw_null_ostream, but it's better to have raw_null_ostream follow
     796             :   // the rules than to change the rules just for raw_null_ostream.
     797             :   flush();
     798             : #endif
     799      790151 : }
     800             : 
     801           0 : void raw_null_ostream::write_impl(const char *Ptr, size_t Size) {
     802           0 : }
     803             : 
     804           0 : uint64_t raw_null_ostream::current_pos() const {
     805           0 :   return 0;
     806             : }
     807             : 
     808           0 : void raw_null_ostream::pwrite_impl(const char *Ptr, size_t Size,
     809           0 :                                    uint64_t Offset) {}

Generated by: LCOV version 1.13