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 template <char C>
459 static raw_ostream &write_padding(raw_ostream &OS, unsigned NumChars) {
460   static const char Chars[] = {C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C,
461                                C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C,
462                                C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C,
463                                C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C,
464                                C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C};
465 
466   // Usually the indentation is small, handle it with a fastpath.
467   if (NumChars < array_lengthof(Chars))
468     return OS.write(Chars, NumChars);
469 
470   while (NumChars) {
471     unsigned NumToWrite = std::min(NumChars,
472                                    (unsigned)array_lengthof(Chars)-1);
473     OS.write(Chars, NumToWrite);
474     NumChars -= NumToWrite;
475   }
476   return OS;
477 }
478 
479 /// indent - Insert 'NumSpaces' spaces.
480 raw_ostream &raw_ostream::indent(unsigned NumSpaces) {
481   return write_padding<' '>(*this, NumSpaces);
482 }
483 
484 /// write_zeros - Insert 'NumZeros' nulls.
485 raw_ostream &raw_ostream::write_zeros(unsigned NumZeros) {
486   return write_padding<'\0'>(*this, NumZeros);
487 }
488 
489 void raw_ostream::anchor() {}
490 
491 //===----------------------------------------------------------------------===//
492 //  Formatted Output
493 //===----------------------------------------------------------------------===//
494 
495 // Out of line virtual method.
496 void format_object_base::home() {
497 }
498 
499 //===----------------------------------------------------------------------===//
500 //  raw_fd_ostream
501 //===----------------------------------------------------------------------===//
502 
503 static int getFD(StringRef Filename, std::error_code &EC,
504                  sys::fs::OpenFlags Flags) {
505   // Handle "-" as stdout. Note that when we do this, we consider ourself
506   // the owner of stdout and may set the "binary" flag globally based on Flags.
507   if (Filename == "-") {
508     EC = std::error_code();
509     // If user requested binary then put stdout into binary mode if
510     // possible.
511     if (!(Flags & sys::fs::F_Text))
512       sys::ChangeStdoutToBinary();
513     return STDOUT_FILENO;
514   }
515 
516   int FD;
517   EC = sys::fs::openFileForWrite(Filename, FD, Flags);
518   if (EC)
519     return -1;
520 
521   return FD;
522 }
523 
524 raw_fd_ostream::raw_fd_ostream(StringRef Filename, std::error_code &EC,
525                                sys::fs::OpenFlags Flags)
526     : raw_fd_ostream(getFD(Filename, EC, Flags), true) {}
527 
528 /// FD is the file descriptor that this writes to.  If ShouldClose is true, this
529 /// closes the file when the stream is destroyed.
530 raw_fd_ostream::raw_fd_ostream(int fd, bool shouldClose, bool unbuffered)
531     : raw_pwrite_stream(unbuffered), FD(fd), ShouldClose(shouldClose) {
532   if (FD < 0 ) {
533     ShouldClose = false;
534     return;
535   }
536 
537   // Do not attempt to close stdout or stderr. We used to try to maintain the
538   // property that tools that support writing file to stdout should not also
539   // write informational output to stdout, but in practice we were never able to
540   // maintain this invariant. Many features have been added to LLVM and clang
541   // (-fdump-record-layouts, optimization remarks, etc) that print to stdout, so
542   // users must simply be aware that mixed output and remarks is a possibility.
543   if (FD <= STDERR_FILENO)
544     ShouldClose = false;
545 
546   // Get the starting position.
547   off_t loc = ::lseek(FD, 0, SEEK_CUR);
548 #ifdef _WIN32
549   // MSVCRT's _lseek(SEEK_CUR) doesn't return -1 for pipes.
550   sys::fs::file_status Status;
551   std::error_code EC = status(FD, Status);
552   SupportsSeeking = !EC && Status.type() == sys::fs::file_type::regular_file;
553 #else
554   SupportsSeeking = loc != (off_t)-1;
555 #endif
556   if (!SupportsSeeking)
557     pos = 0;
558   else
559     pos = static_cast<uint64_t>(loc);
560 }
561 
562 raw_fd_ostream::~raw_fd_ostream() {
563   if (FD >= 0) {
564     flush();
565     if (ShouldClose) {
566       if (auto EC = sys::Process::SafelyCloseFileDescriptor(FD))
567         error_detected(EC);
568     }
569   }
570 
571 #ifdef __MINGW32__
572   // On mingw, global dtors should not call exit().
573   // report_fatal_error() invokes exit(). We know report_fatal_error()
574   // might not write messages to stderr when any errors were detected
575   // on FD == 2.
576   if (FD == 2) return;
577 #endif
578 
579   // If there are any pending errors, report them now. Clients wishing
580   // to avoid report_fatal_error calls should check for errors with
581   // has_error() and clear the error flag with clear_error() before
582   // destructing raw_ostream objects which may have errors.
583   if (has_error())
584     report_fatal_error("IO failure on output stream: " + error().message(),
585                        /*GenCrashDiag=*/false);
586 }
587 
588 void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) {
589   assert(FD >= 0 && "File already closed.");
590   pos += Size;
591 
592   // The maximum write size is limited to SSIZE_MAX because a write
593   // greater than SSIZE_MAX is implementation-defined in POSIX.
594   // Since SSIZE_MAX is not portable, we use SIZE_MAX >> 1 instead.
595   size_t MaxWriteSize = SIZE_MAX >> 1;
596 
597 #if defined(__linux__)
598   // It is observed that Linux returns EINVAL for a very large write (>2G).
599   // Make it a reasonably small value.
600   MaxWriteSize = 1024 * 1024 * 1024;
601 #elif defined(_WIN32)
602   // Writing a large size of output to Windows console returns ENOMEM. It seems
603   // that, prior to Windows 8, WriteFile() is redirecting to WriteConsole(), and
604   // the latter has a size limit (66000 bytes or less, depending on heap usage).
605   if (::_isatty(FD) && !RunningWindows8OrGreater())
606     MaxWriteSize = 32767;
607 #endif
608 
609   do {
610     size_t ChunkSize = std::min(Size, MaxWriteSize);
611     ssize_t ret = ::write(FD, Ptr, ChunkSize);
612 
613     if (ret < 0) {
614       // If it's a recoverable error, swallow it and retry the write.
615       //
616       // Ideally we wouldn't ever see EAGAIN or EWOULDBLOCK here, since
617       // raw_ostream isn't designed to do non-blocking I/O. However, some
618       // programs, such as old versions of bjam, have mistakenly used
619       // O_NONBLOCK. For compatibility, emulate blocking semantics by
620       // spinning until the write succeeds. If you don't want spinning,
621       // don't use O_NONBLOCK file descriptors with raw_ostream.
622       if (errno == EINTR || errno == EAGAIN
623 #ifdef EWOULDBLOCK
624           || errno == EWOULDBLOCK
625 #endif
626           )
627         continue;
628 
629       // Otherwise it's a non-recoverable error. Note it and quit.
630       error_detected(std::error_code(errno, std::generic_category()));
631       break;
632     }
633 
634     // The write may have written some or all of the data. Update the
635     // size and buffer pointer to reflect the remainder that needs
636     // to be written. If there are no bytes left, we're done.
637     Ptr += ret;
638     Size -= ret;
639   } while (Size > 0);
640 }
641 
642 void raw_fd_ostream::close() {
643   assert(ShouldClose);
644   ShouldClose = false;
645   flush();
646   if (auto EC = sys::Process::SafelyCloseFileDescriptor(FD))
647     error_detected(EC);
648   FD = -1;
649 }
650 
651 uint64_t raw_fd_ostream::seek(uint64_t off) {
652   assert(SupportsSeeking && "Stream does not support seeking!");
653   flush();
654 #ifdef _WIN32
655   pos = ::_lseeki64(FD, off, SEEK_SET);
656 #elif defined(HAVE_LSEEK64)
657   pos = ::lseek64(FD, off, SEEK_SET);
658 #else
659   pos = ::lseek(FD, off, SEEK_SET);
660 #endif
661   if (pos == (uint64_t)-1)
662     error_detected(std::error_code(errno, std::generic_category()));
663   return pos;
664 }
665 
666 void raw_fd_ostream::pwrite_impl(const char *Ptr, size_t Size,
667                                  uint64_t Offset) {
668   uint64_t Pos = tell();
669   seek(Offset);
670   write(Ptr, Size);
671   seek(Pos);
672 }
673 
674 size_t raw_fd_ostream::preferred_buffer_size() const {
675 #if !defined(_MSC_VER) && !defined(__MINGW32__) && !defined(__minix)
676   // Windows and Minix have no st_blksize.
677   assert(FD >= 0 && "File not yet open!");
678   struct stat statbuf;
679   if (fstat(FD, &statbuf) != 0)
680     return 0;
681 
682   // If this is a terminal, don't use buffering. Line buffering
683   // would be a more traditional thing to do, but it's not worth
684   // the complexity.
685   if (S_ISCHR(statbuf.st_mode) && isatty(FD))
686     return 0;
687   // Return the preferred block size.
688   return statbuf.st_blksize;
689 #else
690   return raw_ostream::preferred_buffer_size();
691 #endif
692 }
693 
694 raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold,
695                                          bool bg) {
696   if (sys::Process::ColorNeedsFlush())
697     flush();
698   const char *colorcode =
699     (colors == SAVEDCOLOR) ? sys::Process::OutputBold(bg)
700     : sys::Process::OutputColor(colors, bold, bg);
701   if (colorcode) {
702     size_t len = strlen(colorcode);
703     write(colorcode, len);
704     // don't account colors towards output characters
705     pos -= len;
706   }
707   return *this;
708 }
709 
710 raw_ostream &raw_fd_ostream::resetColor() {
711   if (sys::Process::ColorNeedsFlush())
712     flush();
713   const char *colorcode = sys::Process::ResetColor();
714   if (colorcode) {
715     size_t len = strlen(colorcode);
716     write(colorcode, len);
717     // don't account colors towards output characters
718     pos -= len;
719   }
720   return *this;
721 }
722 
723 raw_ostream &raw_fd_ostream::reverseColor() {
724   if (sys::Process::ColorNeedsFlush())
725     flush();
726   const char *colorcode = sys::Process::OutputReverse();
727   if (colorcode) {
728     size_t len = strlen(colorcode);
729     write(colorcode, len);
730     // don't account colors towards output characters
731     pos -= len;
732   }
733   return *this;
734 }
735 
736 bool raw_fd_ostream::is_displayed() const {
737   return sys::Process::FileDescriptorIsDisplayed(FD);
738 }
739 
740 bool raw_fd_ostream::has_colors() const {
741   return sys::Process::FileDescriptorHasColors(FD);
742 }
743 
744 void raw_fd_ostream::anchor() {}
745 
746 //===----------------------------------------------------------------------===//
747 //  outs(), errs(), nulls()
748 //===----------------------------------------------------------------------===//
749 
750 /// outs() - This returns a reference to a raw_ostream for standard output.
751 /// Use it like: outs() << "foo" << "bar";
752 raw_ostream &llvm::outs() {
753   // Set buffer settings to model stdout behavior.
754   std::error_code EC;
755   static raw_fd_ostream S("-", EC, sys::fs::F_None);
756   assert(!EC);
757   return S;
758 }
759 
760 /// errs() - This returns a reference to a raw_ostream for standard error.
761 /// Use it like: errs() << "foo" << "bar";
762 raw_ostream &llvm::errs() {
763   // Set standard error to be unbuffered by default.
764   static raw_fd_ostream S(STDERR_FILENO, false, true);
765   return S;
766 }
767 
768 /// nulls() - This returns a reference to a raw_ostream which discards output.
769 raw_ostream &llvm::nulls() {
770   static raw_null_ostream S;
771   return S;
772 }
773 
774 //===----------------------------------------------------------------------===//
775 //  raw_string_ostream
776 //===----------------------------------------------------------------------===//
777 
778 raw_string_ostream::~raw_string_ostream() {
779   flush();
780 }
781 
782 void raw_string_ostream::write_impl(const char *Ptr, size_t Size) {
783   OS.append(Ptr, Size);
784 }
785 
786 //===----------------------------------------------------------------------===//
787 //  raw_svector_ostream
788 //===----------------------------------------------------------------------===//
789 
790 uint64_t raw_svector_ostream::current_pos() const { return OS.size(); }
791 
792 void raw_svector_ostream::write_impl(const char *Ptr, size_t Size) {
793   OS.append(Ptr, Ptr + Size);
794 }
795 
796 void raw_svector_ostream::pwrite_impl(const char *Ptr, size_t Size,
797                                       uint64_t Offset) {
798   memcpy(OS.data() + Offset, Ptr, Size);
799 }
800 
801 //===----------------------------------------------------------------------===//
802 //  raw_null_ostream
803 //===----------------------------------------------------------------------===//
804 
805 raw_null_ostream::~raw_null_ostream() {
806 #ifndef NDEBUG
807   // ~raw_ostream asserts that the buffer is empty. This isn't necessary
808   // with raw_null_ostream, but it's better to have raw_null_ostream follow
809   // the rules than to change the rules just for raw_null_ostream.
810   flush();
811 #endif
812 }
813 
814 void raw_null_ostream::write_impl(const char *Ptr, size_t Size) {
815 }
816 
817 uint64_t raw_null_ostream::current_pos() const {
818   return 0;
819 }
820 
821 void raw_null_ostream::pwrite_impl(const char *Ptr, size_t Size,
822                                    uint64_t Offset) {}
823 
824 void raw_pwrite_stream::anchor() {}
825