• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
~raw_ostream()71 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   if (BufferMode == InternalBuffer)
78     delete [] OutBufStart;
79 }
80 
81 // An out of line virtual method to provide a home for the class vtable.
handle()82 void raw_ostream::handle() {}
83 
preferred_buffer_size() const84 size_t raw_ostream::preferred_buffer_size() const {
85   // BUFSIZ is intended to be a reasonable default.
86   return BUFSIZ;
87 }
88 
SetBuffered()89 void raw_ostream::SetBuffered() {
90   // Ask the subclass to determine an appropriate buffer size.
91   if (size_t Size = preferred_buffer_size())
92     SetBufferSize(Size);
93   else
94     // It may return 0, meaning this stream should be unbuffered.
95     SetUnbuffered();
96 }
97 
SetBufferAndMode(char * BufferStart,size_t Size,BufferKind Mode)98 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   if (BufferMode == InternalBuffer)
108     delete [] OutBufStart;
109   OutBufStart = BufferStart;
110   OutBufEnd = OutBufStart+Size;
111   OutBufCur = OutBufStart;
112   BufferMode = Mode;
113 
114   assert(OutBufStart <= OutBufEnd && "Invalid size!");
115 }
116 
operator <<(unsigned long N)117 raw_ostream &raw_ostream::operator<<(unsigned long N) {
118   write_integer(*this, static_cast<uint64_t>(N), 0, IntegerStyle::Integer);
119   return *this;
120 }
121 
operator <<(long N)122 raw_ostream &raw_ostream::operator<<(long N) {
123   write_integer(*this, static_cast<int64_t>(N), 0, IntegerStyle::Integer);
124   return *this;
125 }
126 
operator <<(unsigned long long N)127 raw_ostream &raw_ostream::operator<<(unsigned long long N) {
128   write_integer(*this, static_cast<uint64_t>(N), 0, IntegerStyle::Integer);
129   return *this;
130 }
131 
operator <<(long long N)132 raw_ostream &raw_ostream::operator<<(long long N) {
133   write_integer(*this, static_cast<int64_t>(N), 0, IntegerStyle::Integer);
134   return *this;
135 }
136 
write_hex(unsigned long long N)137 raw_ostream &raw_ostream::write_hex(unsigned long long N) {
138   llvm::write_hex(*this, N, HexPrintStyle::Lower);
139   return *this;
140 }
141 
write_escaped(StringRef Str,bool UseHexEscapes)142 raw_ostream &raw_ostream::write_escaped(StringRef Str,
143                                         bool UseHexEscapes) {
144   for (unsigned char c : Str) {
145     switch (c) {
146     case '\\':
147       *this << '\\' << '\\';
148       break;
149     case '\t':
150       *this << '\\' << 't';
151       break;
152     case '\n':
153       *this << '\\' << 'n';
154       break;
155     case '"':
156       *this << '\\' << '"';
157       break;
158     default:
159       if (std::isprint(c)) {
160         *this << c;
161         break;
162       }
163 
164       // Write out the escaped representation.
165       if (UseHexEscapes) {
166         *this << '\\' << 'x';
167         *this << hexdigit((c >> 4 & 0xF));
168         *this << hexdigit((c >> 0) & 0xF);
169       } else {
170         // Always use a full 3-character octal escape.
171         *this << '\\';
172         *this << char('0' + ((c >> 6) & 7));
173         *this << char('0' + ((c >> 3) & 7));
174         *this << char('0' + ((c >> 0) & 7));
175       }
176     }
177   }
178 
179   return *this;
180 }
181 
operator <<(const void * P)182 raw_ostream &raw_ostream::operator<<(const void *P) {
183   llvm::write_hex(*this, (uintptr_t)P, HexPrintStyle::PrefixLower);
184   return *this;
185 }
186 
operator <<(double N)187 raw_ostream &raw_ostream::operator<<(double N) {
188   llvm::write_double(*this, N, FloatStyle::Exponent);
189   return *this;
190 }
191 
flush_nonempty()192 void raw_ostream::flush_nonempty() {
193   assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty.");
194   size_t Length = OutBufCur - OutBufStart;
195   OutBufCur = OutBufStart;
196   write_impl(OutBufStart, Length);
197 }
198 
write(unsigned char C)199 raw_ostream &raw_ostream::write(unsigned char C) {
200   // Group exceptional cases into a single branch.
201   if (LLVM_UNLIKELY(OutBufCur >= OutBufEnd)) {
202     if (LLVM_UNLIKELY(!OutBufStart)) {
203       if (BufferMode == Unbuffered) {
204         write_impl(reinterpret_cast<char*>(&C), 1);
205         return *this;
206       }
207       // Set up a buffer and start over.
208       SetBuffered();
209       return write(C);
210     }
211 
212     flush_nonempty();
213   }
214 
215   *OutBufCur++ = C;
216   return *this;
217 }
218 
write(const char * Ptr,size_t Size)219 raw_ostream &raw_ostream::write(const char *Ptr, size_t Size) {
220   // Group exceptional cases into a single branch.
221   if (LLVM_UNLIKELY(size_t(OutBufEnd - OutBufCur) < Size)) {
222     if (LLVM_UNLIKELY(!OutBufStart)) {
223       if (BufferMode == Unbuffered) {
224         write_impl(Ptr, Size);
225         return *this;
226       }
227       // Set up a buffer and start over.
228       SetBuffered();
229       return write(Ptr, Size);
230     }
231 
232     size_t NumBytes = OutBufEnd - OutBufCur;
233 
234     // If the buffer is empty at this point we have a string that is larger
235     // than the buffer. Directly write the chunk that is a multiple of the
236     // preferred buffer size and put the remainder in the buffer.
237     if (LLVM_UNLIKELY(OutBufCur == OutBufStart)) {
238       assert(NumBytes != 0 && "undefined behavior");
239       size_t BytesToWrite = Size - (Size % NumBytes);
240       write_impl(Ptr, BytesToWrite);
241       size_t BytesRemaining = Size - BytesToWrite;
242       if (BytesRemaining > size_t(OutBufEnd - OutBufCur)) {
243         // Too much left over to copy into our buffer.
244         return write(Ptr + BytesToWrite, BytesRemaining);
245       }
246       copy_to_buffer(Ptr + BytesToWrite, BytesRemaining);
247       return *this;
248     }
249 
250     // We don't have enough space in the buffer to fit the string in. Insert as
251     // much as possible, flush and start over with the remainder.
252     copy_to_buffer(Ptr, NumBytes);
253     flush_nonempty();
254     return write(Ptr + NumBytes, Size - NumBytes);
255   }
256 
257   copy_to_buffer(Ptr, Size);
258 
259   return *this;
260 }
261 
copy_to_buffer(const char * Ptr,size_t Size)262 void raw_ostream::copy_to_buffer(const char *Ptr, size_t Size) {
263   assert(Size <= size_t(OutBufEnd - OutBufCur) && "Buffer overrun!");
264 
265   // Handle short strings specially, memcpy isn't very good at very short
266   // strings.
267   switch (Size) {
268   case 4: OutBufCur[3] = Ptr[3]; LLVM_FALLTHROUGH;
269   case 3: OutBufCur[2] = Ptr[2]; LLVM_FALLTHROUGH;
270   case 2: OutBufCur[1] = Ptr[1]; LLVM_FALLTHROUGH;
271   case 1: OutBufCur[0] = Ptr[0]; LLVM_FALLTHROUGH;
272   case 0: break;
273   default:
274     memcpy(OutBufCur, Ptr, Size);
275     break;
276   }
277 
278   OutBufCur += Size;
279 }
280 
281 // Formatted output.
operator <<(const format_object_base & Fmt)282 raw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) {
283   // If we have more than a few bytes left in our output buffer, try
284   // formatting directly onto its end.
285   size_t NextBufferSize = 127;
286   size_t BufferBytesLeft = OutBufEnd - OutBufCur;
287   if (BufferBytesLeft > 3) {
288     size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft);
289 
290     // Common case is that we have plenty of space.
291     if (BytesUsed <= BufferBytesLeft) {
292       OutBufCur += BytesUsed;
293       return *this;
294     }
295 
296     // Otherwise, we overflowed and the return value tells us the size to try
297     // again with.
298     NextBufferSize = BytesUsed;
299   }
300 
301   // If we got here, we didn't have enough space in the output buffer for the
302   // string.  Try printing into a SmallVector that is resized to have enough
303   // space.  Iterate until we win.
304   SmallVector<char, 128> V;
305 
306   while (true) {
307     V.resize(NextBufferSize);
308 
309     // Try formatting into the SmallVector.
310     size_t BytesUsed = Fmt.print(V.data(), NextBufferSize);
311 
312     // If BytesUsed fit into the vector, we win.
313     if (BytesUsed <= NextBufferSize)
314       return write(V.data(), BytesUsed);
315 
316     // Otherwise, try again with a new size.
317     assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?");
318     NextBufferSize = BytesUsed;
319   }
320 }
321 
operator <<(const formatv_object_base & Obj)322 raw_ostream &raw_ostream::operator<<(const formatv_object_base &Obj) {
323   SmallString<128> S;
324   Obj.format(*this);
325   return *this;
326 }
327 
operator <<(const FormattedString & FS)328 raw_ostream &raw_ostream::operator<<(const FormattedString &FS) {
329   unsigned Len = FS.Str.size();
330   int PadAmount = FS.Width - Len;
331   if (FS.RightJustify && (PadAmount > 0))
332     this->indent(PadAmount);
333   this->operator<<(FS.Str);
334   if (!FS.RightJustify && (PadAmount > 0))
335     this->indent(PadAmount);
336   return *this;
337 }
338 
operator <<(const FormattedNumber & FN)339 raw_ostream &raw_ostream::operator<<(const FormattedNumber &FN) {
340   if (FN.Hex) {
341     HexPrintStyle Style;
342     if (FN.Upper && FN.HexPrefix)
343       Style = HexPrintStyle::PrefixUpper;
344     else if (FN.Upper && !FN.HexPrefix)
345       Style = HexPrintStyle::Upper;
346     else if (!FN.Upper && FN.HexPrefix)
347       Style = HexPrintStyle::PrefixLower;
348     else
349       Style = HexPrintStyle::Lower;
350     llvm::write_hex(*this, FN.HexValue, Style, FN.Width);
351   } else {
352     llvm::SmallString<16> Buffer;
353     llvm::raw_svector_ostream Stream(Buffer);
354     llvm::write_integer(Stream, FN.DecValue, 0, IntegerStyle::Integer);
355     if (Buffer.size() < FN.Width)
356       indent(FN.Width - Buffer.size());
357     (*this) << Buffer;
358   }
359   return *this;
360 }
361 
operator <<(const FormattedBytes & FB)362 raw_ostream &raw_ostream::operator<<(const FormattedBytes &FB) {
363   if (FB.Bytes.empty())
364     return *this;
365 
366   size_t LineIndex = 0;
367   auto Bytes = FB.Bytes;
368   const size_t Size = Bytes.size();
369   HexPrintStyle HPS = FB.Upper ? HexPrintStyle::Upper : HexPrintStyle::Lower;
370   uint64_t OffsetWidth = 0;
371   if (FB.FirstByteOffset.hasValue()) {
372     // Figure out how many nibbles are needed to print the largest offset
373     // represented by this data set, so that we can align the offset field
374     // to the right width.
375     size_t Lines = Size / FB.NumPerLine;
376     uint64_t MaxOffset = *FB.FirstByteOffset + Lines * FB.NumPerLine;
377     unsigned Power = 0;
378     if (MaxOffset > 0)
379       Power = llvm::Log2_64_Ceil(MaxOffset);
380     OffsetWidth = std::max<uint64_t>(4, llvm::alignTo(Power, 4) / 4);
381   }
382 
383   // The width of a block of data including all spaces for group separators.
384   unsigned NumByteGroups =
385       alignTo(FB.NumPerLine, FB.ByteGroupSize) / FB.ByteGroupSize;
386   unsigned BlockCharWidth = FB.NumPerLine * 2 + NumByteGroups - 1;
387 
388   while (!Bytes.empty()) {
389     indent(FB.IndentLevel);
390 
391     if (FB.FirstByteOffset.hasValue()) {
392       uint64_t Offset = FB.FirstByteOffset.getValue();
393       llvm::write_hex(*this, Offset + LineIndex, HPS, OffsetWidth);
394       *this << ": ";
395     }
396 
397     auto Line = Bytes.take_front(FB.NumPerLine);
398 
399     size_t CharsPrinted = 0;
400     // Print the hex bytes for this line in groups
401     for (size_t I = 0; I < Line.size(); ++I, CharsPrinted += 2) {
402       if (I && (I % FB.ByteGroupSize) == 0) {
403         ++CharsPrinted;
404         *this << " ";
405       }
406       llvm::write_hex(*this, Line[I], HPS, 2);
407     }
408 
409     if (FB.ASCII) {
410       // Print any spaces needed for any bytes that we didn't print on this
411       // line so that the ASCII bytes are correctly aligned.
412       assert(BlockCharWidth >= CharsPrinted);
413       indent(BlockCharWidth - CharsPrinted + 2);
414       *this << "|";
415 
416       // Print the ASCII char values for each byte on this line
417       for (uint8_t Byte : Line) {
418         if (isprint(Byte))
419           *this << static_cast<char>(Byte);
420         else
421           *this << '.';
422       }
423       *this << '|';
424     }
425 
426     Bytes = Bytes.drop_front(Line.size());
427     LineIndex += Line.size();
428     if (LineIndex < Size)
429       *this << '\n';
430   }
431   return *this;
432 }
433 
434 /// indent - Insert 'NumSpaces' spaces.
indent(unsigned NumSpaces)435 raw_ostream &raw_ostream::indent(unsigned NumSpaces) {
436   static const char Spaces[] = "                                "
437                                "                                "
438                                "                ";
439 
440   // Usually the indentation is small, handle it with a fastpath.
441   if (NumSpaces < array_lengthof(Spaces))
442     return write(Spaces, NumSpaces);
443 
444   while (NumSpaces) {
445     unsigned NumToWrite = std::min(NumSpaces,
446                                    (unsigned)array_lengthof(Spaces)-1);
447     write(Spaces, NumToWrite);
448     NumSpaces -= NumToWrite;
449   }
450   return *this;
451 }
452 
453 //===----------------------------------------------------------------------===//
454 //  Formatted Output
455 //===----------------------------------------------------------------------===//
456 
457 // Out of line virtual method.
home()458 void format_object_base::home() {
459 }
460 
461 //===----------------------------------------------------------------------===//
462 //  raw_fd_ostream
463 //===----------------------------------------------------------------------===//
464 
getFD(StringRef Filename,std::error_code & EC,sys::fs::OpenFlags Flags)465 static int getFD(StringRef Filename, std::error_code &EC,
466                  sys::fs::OpenFlags Flags) {
467   // Handle "-" as stdout. Note that when we do this, we consider ourself
468   // the owner of stdout. This means that we can do things like close the
469   // file descriptor when we're done and set the "binary" flag globally.
470   if (Filename == "-") {
471     EC = std::error_code();
472     // If user requested binary then put stdout into binary mode if
473     // possible.
474     if (!(Flags & sys::fs::F_Text))
475       sys::ChangeStdoutToBinary();
476     return STDOUT_FILENO;
477   }
478 
479   int FD;
480   EC = sys::fs::openFileForWrite(Filename, FD, Flags);
481   if (EC)
482     return -1;
483 
484   return FD;
485 }
486 
raw_fd_ostream(StringRef Filename,std::error_code & EC,sys::fs::OpenFlags Flags)487 raw_fd_ostream::raw_fd_ostream(StringRef Filename, std::error_code &EC,
488                                sys::fs::OpenFlags Flags)
489     : raw_fd_ostream(getFD(Filename, EC, Flags), true) {}
490 
491 /// FD is the file descriptor that this writes to.  If ShouldClose is true, this
492 /// closes the file when the stream is destroyed.
raw_fd_ostream(int fd,bool shouldClose,bool unbuffered)493 raw_fd_ostream::raw_fd_ostream(int fd, bool shouldClose, bool unbuffered)
494     : raw_pwrite_stream(unbuffered), FD(fd), ShouldClose(shouldClose),
495       Error(false) {
496   if (FD < 0 ) {
497     ShouldClose = false;
498     return;
499   }
500 
501   // Get the starting position.
502   off_t loc = ::lseek(FD, 0, SEEK_CUR);
503 #ifdef LLVM_ON_WIN32
504   // MSVCRT's _lseek(SEEK_CUR) doesn't return -1 for pipes.
505   sys::fs::file_status Status;
506   std::error_code EC = status(FD, Status);
507   SupportsSeeking = !EC && Status.type() == sys::fs::file_type::regular_file;
508 #else
509   SupportsSeeking = loc != (off_t)-1;
510 #endif
511   if (!SupportsSeeking)
512     pos = 0;
513   else
514     pos = static_cast<uint64_t>(loc);
515 }
516 
~raw_fd_ostream()517 raw_fd_ostream::~raw_fd_ostream() {
518   if (FD >= 0) {
519     flush();
520     if (ShouldClose && sys::Process::SafelyCloseFileDescriptor(FD))
521       error_detected();
522   }
523 
524 #ifdef __MINGW32__
525   // On mingw, global dtors should not call exit().
526   // report_fatal_error() invokes exit(). We know report_fatal_error()
527   // might not write messages to stderr when any errors were detected
528   // on FD == 2.
529   if (FD == 2) return;
530 #endif
531 
532   // If there are any pending errors, report them now. Clients wishing
533   // to avoid report_fatal_error calls should check for errors with
534   // has_error() and clear the error flag with clear_error() before
535   // destructing raw_ostream objects which may have errors.
536   if (has_error())
537     report_fatal_error("IO failure on output stream.", /*GenCrashDiag=*/false);
538 }
539 
write_impl(const char * Ptr,size_t Size)540 void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) {
541   assert(FD >= 0 && "File already closed.");
542   pos += Size;
543 
544 #ifndef LLVM_ON_WIN32
545   bool ShouldWriteInChunks = false;
546 #else
547   // Writing a large size of output to Windows console returns ENOMEM. It seems
548   // that, prior to Windows 8, WriteFile() is redirecting to WriteConsole(), and
549   // the latter has a size limit (66000 bytes or less, depending on heap usage).
550   bool ShouldWriteInChunks = !!::_isatty(FD) && !RunningWindows8OrGreater();
551 #endif
552 
553   do {
554     size_t ChunkSize = Size;
555     if (ChunkSize > 32767 && ShouldWriteInChunks)
556         ChunkSize = 32767;
557 
558     ssize_t ret = ::write(FD, Ptr, ChunkSize);
559 
560     if (ret < 0) {
561       // If it's a recoverable error, swallow it and retry the write.
562       //
563       // Ideally we wouldn't ever see EAGAIN or EWOULDBLOCK here, since
564       // raw_ostream isn't designed to do non-blocking I/O. However, some
565       // programs, such as old versions of bjam, have mistakenly used
566       // O_NONBLOCK. For compatibility, emulate blocking semantics by
567       // spinning until the write succeeds. If you don't want spinning,
568       // don't use O_NONBLOCK file descriptors with raw_ostream.
569       if (errno == EINTR || errno == EAGAIN
570 #ifdef EWOULDBLOCK
571           || errno == EWOULDBLOCK
572 #endif
573           )
574         continue;
575 
576       // Otherwise it's a non-recoverable error. Note it and quit.
577       error_detected();
578       break;
579     }
580 
581     // The write may have written some or all of the data. Update the
582     // size and buffer pointer to reflect the remainder that needs
583     // to be written. If there are no bytes left, we're done.
584     Ptr += ret;
585     Size -= ret;
586   } while (Size > 0);
587 }
588 
close()589 void raw_fd_ostream::close() {
590   assert(ShouldClose);
591   ShouldClose = false;
592   flush();
593   if (sys::Process::SafelyCloseFileDescriptor(FD))
594     error_detected();
595   FD = -1;
596 }
597 
seek(uint64_t off)598 uint64_t raw_fd_ostream::seek(uint64_t off) {
599   assert(SupportsSeeking && "Stream does not support seeking!");
600   flush();
601 #ifdef LLVM_ON_WIN32
602   pos = ::_lseeki64(FD, off, SEEK_SET);
603 #elif defined(HAVE_LSEEK64)
604   pos = ::lseek64(FD, off, SEEK_SET);
605 #else
606   pos = ::lseek(FD, off, SEEK_SET);
607 #endif
608   if (pos == (uint64_t)-1)
609     error_detected();
610   return pos;
611 }
612 
pwrite_impl(const char * Ptr,size_t Size,uint64_t Offset)613 void raw_fd_ostream::pwrite_impl(const char *Ptr, size_t Size,
614                                  uint64_t Offset) {
615   uint64_t Pos = tell();
616   seek(Offset);
617   write(Ptr, Size);
618   seek(Pos);
619 }
620 
preferred_buffer_size() const621 size_t raw_fd_ostream::preferred_buffer_size() const {
622 #if !defined(_MSC_VER) && !defined(__MINGW32__) && !defined(__minix)
623   // Windows and Minix have no st_blksize.
624   assert(FD >= 0 && "File not yet open!");
625   struct stat statbuf;
626   if (fstat(FD, &statbuf) != 0)
627     return 0;
628 
629   // If this is a terminal, don't use buffering. Line buffering
630   // would be a more traditional thing to do, but it's not worth
631   // the complexity.
632   if (S_ISCHR(statbuf.st_mode) && isatty(FD))
633     return 0;
634   // Return the preferred block size.
635   return statbuf.st_blksize;
636 #else
637   return raw_ostream::preferred_buffer_size();
638 #endif
639 }
640 
changeColor(enum Colors colors,bool bold,bool bg)641 raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold,
642                                          bool bg) {
643   if (sys::Process::ColorNeedsFlush())
644     flush();
645   const char *colorcode =
646     (colors == SAVEDCOLOR) ? sys::Process::OutputBold(bg)
647     : sys::Process::OutputColor(colors, bold, bg);
648   if (colorcode) {
649     size_t len = strlen(colorcode);
650     write(colorcode, len);
651     // don't account colors towards output characters
652     pos -= len;
653   }
654   return *this;
655 }
656 
resetColor()657 raw_ostream &raw_fd_ostream::resetColor() {
658   if (sys::Process::ColorNeedsFlush())
659     flush();
660   const char *colorcode = sys::Process::ResetColor();
661   if (colorcode) {
662     size_t len = strlen(colorcode);
663     write(colorcode, len);
664     // don't account colors towards output characters
665     pos -= len;
666   }
667   return *this;
668 }
669 
reverseColor()670 raw_ostream &raw_fd_ostream::reverseColor() {
671   if (sys::Process::ColorNeedsFlush())
672     flush();
673   const char *colorcode = sys::Process::OutputReverse();
674   if (colorcode) {
675     size_t len = strlen(colorcode);
676     write(colorcode, len);
677     // don't account colors towards output characters
678     pos -= len;
679   }
680   return *this;
681 }
682 
is_displayed() const683 bool raw_fd_ostream::is_displayed() const {
684   return sys::Process::FileDescriptorIsDisplayed(FD);
685 }
686 
has_colors() const687 bool raw_fd_ostream::has_colors() const {
688   return sys::Process::FileDescriptorHasColors(FD);
689 }
690 
691 //===----------------------------------------------------------------------===//
692 //  outs(), errs(), nulls()
693 //===----------------------------------------------------------------------===//
694 
695 /// outs() - This returns a reference to a raw_ostream for standard output.
696 /// Use it like: outs() << "foo" << "bar";
outs()697 raw_ostream &llvm::outs() {
698   // Set buffer settings to model stdout behavior.  Delete the file descriptor
699   // when the program exits, forcing error detection.  This means that if you
700   // ever call outs(), you can't open another raw_fd_ostream on stdout, as we'll
701   // close stdout twice and print an error the second time.
702   std::error_code EC;
703   static raw_fd_ostream S("-", EC, sys::fs::F_None);
704   assert(!EC);
705   return S;
706 }
707 
708 /// errs() - This returns a reference to a raw_ostream for standard error.
709 /// Use it like: errs() << "foo" << "bar";
errs()710 raw_ostream &llvm::errs() {
711   // Set standard error to be unbuffered by default.
712   static raw_fd_ostream S(STDERR_FILENO, false, true);
713   return S;
714 }
715 
716 /// nulls() - This returns a reference to a raw_ostream which discards output.
nulls()717 raw_ostream &llvm::nulls() {
718   static raw_null_ostream S;
719   return S;
720 }
721 
722 //===----------------------------------------------------------------------===//
723 //  raw_string_ostream
724 //===----------------------------------------------------------------------===//
725 
~raw_string_ostream()726 raw_string_ostream::~raw_string_ostream() {
727   flush();
728 }
729 
write_impl(const char * Ptr,size_t Size)730 void raw_string_ostream::write_impl(const char *Ptr, size_t Size) {
731   OS.append(Ptr, Size);
732 }
733 
734 //===----------------------------------------------------------------------===//
735 //  raw_svector_ostream
736 //===----------------------------------------------------------------------===//
737 
current_pos() const738 uint64_t raw_svector_ostream::current_pos() const { return OS.size(); }
739 
write_impl(const char * Ptr,size_t Size)740 void raw_svector_ostream::write_impl(const char *Ptr, size_t Size) {
741   OS.append(Ptr, Ptr + Size);
742 }
743 
pwrite_impl(const char * Ptr,size_t Size,uint64_t Offset)744 void raw_svector_ostream::pwrite_impl(const char *Ptr, size_t Size,
745                                       uint64_t Offset) {
746   memcpy(OS.data() + Offset, Ptr, Size);
747 }
748 
749 //===----------------------------------------------------------------------===//
750 //  raw_null_ostream
751 //===----------------------------------------------------------------------===//
752 
~raw_null_ostream()753 raw_null_ostream::~raw_null_ostream() {
754 #ifndef NDEBUG
755   // ~raw_ostream asserts that the buffer is empty. This isn't necessary
756   // with raw_null_ostream, but it's better to have raw_null_ostream follow
757   // the rules than to change the rules just for raw_null_ostream.
758   flush();
759 #endif
760 }
761 
write_impl(const char * Ptr,size_t Size)762 void raw_null_ostream::write_impl(const char *Ptr, size_t Size) {
763 }
764 
current_pos() const765 uint64_t raw_null_ostream::current_pos() const {
766   return 0;
767 }
768 
pwrite_impl(const char * Ptr,size_t Size,uint64_t Offset)769 void raw_null_ostream::pwrite_impl(const char *Ptr, size_t Size,
770                                    uint64_t Offset) {}
771