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