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/MathExtras.h"
24 #include "llvm/Support/NativeFormatting.h"
25 #include "llvm/Support/Process.h"
26 #include "llvm/Support/Program.h"
27 #include <algorithm>
28 #include <cctype>
29 #include <cerrno>
30 #include <cstdio>
31 #include <iterator>
32 #include <sys/stat.h>
33 #include <system_error>
34 
35 // <fcntl.h> may provide O_BINARY.
36 #if defined(HAVE_FCNTL_H)
37 # include <fcntl.h>
38 #endif
39 
40 #if defined(HAVE_UNISTD_H)
41 # include <unistd.h>
42 #endif
43 #if defined(HAVE_SYS_UIO_H) && defined(HAVE_WRITEV)
44 #  include <sys/uio.h>
45 #endif
46 
47 #if defined(__CYGWIN__)
48 #include <io.h>
49 #endif
50 
51 #if defined(_MSC_VER)
52 #include <io.h>
53 #ifndef STDIN_FILENO
54 # define STDIN_FILENO 0
55 #endif
56 #ifndef STDOUT_FILENO
57 # define STDOUT_FILENO 1
58 #endif
59 #ifndef STDERR_FILENO
60 # define STDERR_FILENO 2
61 #endif
62 #endif
63 
64 #ifdef LLVM_ON_WIN32
65 #include "Windows/WindowsSupport.h"
66 #endif
67 
68 using namespace llvm;
69 
70 raw_ostream::~raw_ostream() {
71   // raw_ostream's subclasses should take care to flush the buffer
72   // in their destructors.
73   assert(OutBufCur == OutBufStart &&
74          "raw_ostream destructor called with non-empty buffer!");
75 
76   if (BufferMode == InternalBuffer)
77     delete [] OutBufStart;
78 }
79 
80 // An out of line virtual method to provide a home for the class vtable.
81 void raw_ostream::handle() {}
82 
83 size_t raw_ostream::preferred_buffer_size() const {
84   // BUFSIZ is intended to be a reasonable default.
85   return BUFSIZ;
86 }
87 
88 void raw_ostream::SetBuffered() {
89   // Ask the subclass to determine an appropriate buffer size.
90   if (size_t Size = preferred_buffer_size())
91     SetBufferSize(Size);
92   else
93     // It may return 0, meaning this stream should be unbuffered.
94     SetUnbuffered();
95 }
96 
97 void raw_ostream::SetBufferAndMode(char *BufferStart, size_t Size,
98                                    BufferKind Mode) {
99   assert(((Mode == Unbuffered && !BufferStart && Size == 0) ||
100           (Mode != Unbuffered && BufferStart && Size != 0)) &&
101          "stream must be unbuffered or have at least one byte");
102   // Make sure the current buffer is free of content (we can't flush here; the
103   // child buffer management logic will be in write_impl).
104   assert(GetNumBytesInBuffer() == 0 && "Current buffer is non-empty!");
105 
106   if (BufferMode == InternalBuffer)
107     delete [] OutBufStart;
108   OutBufStart = BufferStart;
109   OutBufEnd = OutBufStart+Size;
110   OutBufCur = OutBufStart;
111   BufferMode = Mode;
112 
113   assert(OutBufStart <= OutBufEnd && "Invalid size!");
114 }
115 
116 raw_ostream &raw_ostream::operator<<(unsigned long N) {
117   write_ulong(*this, N, 0);
118   return *this;
119 }
120 
121 raw_ostream &raw_ostream::operator<<(long N) {
122   write_long(*this, N, 0);
123   return *this;
124 }
125 
126 raw_ostream &raw_ostream::operator<<(unsigned long long N) {
127   write_ulonglong(*this, N, 0);
128   return *this;
129 }
130 
131 raw_ostream &raw_ostream::operator<<(long long N) {
132   write_longlong(*this, N, 0);
133   return *this;
134 }
135 
136 raw_ostream &raw_ostream::write_hex(unsigned long long N) {
137   llvm::write_hex(*this, N, 0, false, false);
138   return *this;
139 }
140 
141 raw_ostream &raw_ostream::write_escaped(StringRef Str,
142                                         bool UseHexEscapes) {
143   for (unsigned char c : Str) {
144     switch (c) {
145     case '\\':
146       *this << '\\' << '\\';
147       break;
148     case '\t':
149       *this << '\\' << 't';
150       break;
151     case '\n':
152       *this << '\\' << 'n';
153       break;
154     case '"':
155       *this << '\\' << '"';
156       break;
157     default:
158       if (std::isprint(c)) {
159         *this << c;
160         break;
161       }
162 
163       // Write out the escaped representation.
164       if (UseHexEscapes) {
165         *this << '\\' << 'x';
166         *this << hexdigit((c >> 4 & 0xF));
167         *this << hexdigit((c >> 0) & 0xF);
168       } else {
169         // Always use a full 3-character octal escape.
170         *this << '\\';
171         *this << char('0' + ((c >> 6) & 7));
172         *this << char('0' + ((c >> 3) & 7));
173         *this << char('0' + ((c >> 0) & 7));
174       }
175     }
176   }
177 
178   return *this;
179 }
180 
181 raw_ostream &raw_ostream::operator<<(const void *P) {
182   llvm::write_hex(*this, (uintptr_t)P, 0, false, true);
183   return *this;
184 }
185 
186 raw_ostream &raw_ostream::operator<<(double N) {
187   llvm::write_double(*this, N, 0, 0, FloatStyle::Exponent);
188   return *this;
189 }
190 
191 void raw_ostream::flush_nonempty() {
192   assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty.");
193   size_t Length = OutBufCur - OutBufStart;
194   OutBufCur = OutBufStart;
195   write_impl(OutBufStart, Length);
196 }
197 
198 raw_ostream &raw_ostream::write(unsigned char C) {
199   // Group exceptional cases into a single branch.
200   if (LLVM_UNLIKELY(OutBufCur >= OutBufEnd)) {
201     if (LLVM_UNLIKELY(!OutBufStart)) {
202       if (BufferMode == Unbuffered) {
203         write_impl(reinterpret_cast<char*>(&C), 1);
204         return *this;
205       }
206       // Set up a buffer and start over.
207       SetBuffered();
208       return write(C);
209     }
210 
211     flush_nonempty();
212   }
213 
214   *OutBufCur++ = C;
215   return *this;
216 }
217 
218 raw_ostream &raw_ostream::write(const char *Ptr, size_t Size) {
219   // Group exceptional cases into a single branch.
220   if (LLVM_UNLIKELY(size_t(OutBufEnd - OutBufCur) < Size)) {
221     if (LLVM_UNLIKELY(!OutBufStart)) {
222       if (BufferMode == Unbuffered) {
223         write_impl(Ptr, Size);
224         return *this;
225       }
226       // Set up a buffer and start over.
227       SetBuffered();
228       return write(Ptr, Size);
229     }
230 
231     size_t NumBytes = OutBufEnd - OutBufCur;
232 
233     // If the buffer is empty at this point we have a string that is larger
234     // than the buffer. Directly write the chunk that is a multiple of the
235     // preferred buffer size and put the remainder in the buffer.
236     if (LLVM_UNLIKELY(OutBufCur == OutBufStart)) {
237       assert(NumBytes != 0 && "undefined behavior");
238       size_t BytesToWrite = Size - (Size % NumBytes);
239       write_impl(Ptr, BytesToWrite);
240       size_t BytesRemaining = Size - BytesToWrite;
241       if (BytesRemaining > size_t(OutBufEnd - OutBufCur)) {
242         // Too much left over to copy into our buffer.
243         return write(Ptr + BytesToWrite, BytesRemaining);
244       }
245       copy_to_buffer(Ptr + BytesToWrite, BytesRemaining);
246       return *this;
247     }
248 
249     // We don't have enough space in the buffer to fit the string in. Insert as
250     // much as possible, flush and start over with the remainder.
251     copy_to_buffer(Ptr, NumBytes);
252     flush_nonempty();
253     return write(Ptr + NumBytes, Size - NumBytes);
254   }
255 
256   copy_to_buffer(Ptr, Size);
257 
258   return *this;
259 }
260 
261 void raw_ostream::copy_to_buffer(const char *Ptr, size_t Size) {
262   assert(Size <= size_t(OutBufEnd - OutBufCur) && "Buffer overrun!");
263 
264   // Handle short strings specially, memcpy isn't very good at very short
265   // strings.
266   switch (Size) {
267   case 4: OutBufCur[3] = Ptr[3]; LLVM_FALLTHROUGH;
268   case 3: OutBufCur[2] = Ptr[2]; LLVM_FALLTHROUGH;
269   case 2: OutBufCur[1] = Ptr[1]; LLVM_FALLTHROUGH;
270   case 1: OutBufCur[0] = Ptr[0]; LLVM_FALLTHROUGH;
271   case 0: break;
272   default:
273     memcpy(OutBufCur, Ptr, Size);
274     break;
275   }
276 
277   OutBufCur += Size;
278 }
279 
280 // Formatted output.
281 raw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) {
282   // If we have more than a few bytes left in our output buffer, try
283   // formatting directly onto its end.
284   size_t NextBufferSize = 127;
285   size_t BufferBytesLeft = OutBufEnd - OutBufCur;
286   if (BufferBytesLeft > 3) {
287     size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft);
288 
289     // Common case is that we have plenty of space.
290     if (BytesUsed <= BufferBytesLeft) {
291       OutBufCur += BytesUsed;
292       return *this;
293     }
294 
295     // Otherwise, we overflowed and the return value tells us the size to try
296     // again with.
297     NextBufferSize = BytesUsed;
298   }
299 
300   // If we got here, we didn't have enough space in the output buffer for the
301   // string.  Try printing into a SmallVector that is resized to have enough
302   // space.  Iterate until we win.
303   SmallVector<char, 128> V;
304 
305   while (true) {
306     V.resize(NextBufferSize);
307 
308     // Try formatting into the SmallVector.
309     size_t BytesUsed = Fmt.print(V.data(), NextBufferSize);
310 
311     // If BytesUsed fit into the vector, we win.
312     if (BytesUsed <= NextBufferSize)
313       return write(V.data(), BytesUsed);
314 
315     // Otherwise, try again with a new size.
316     assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?");
317     NextBufferSize = BytesUsed;
318   }
319 }
320 
321 raw_ostream &raw_ostream::operator<<(const FormattedString &FS) {
322   unsigned Len = FS.Str.size();
323   int PadAmount = FS.Width - Len;
324   if (FS.RightJustify && (PadAmount > 0))
325     this->indent(PadAmount);
326   this->operator<<(FS.Str);
327   if (!FS.RightJustify && (PadAmount > 0))
328     this->indent(PadAmount);
329   return *this;
330 }
331 
332 raw_ostream &raw_ostream::operator<<(const FormattedNumber &FN) {
333   if (FN.Hex) {
334     llvm::write_hex(*this, FN.HexValue, FN.Width, FN.Upper, FN.HexPrefix);
335   } else {
336     llvm::write_longlong(*this, FN.DecValue, FN.Width);
337   }
338   return *this;
339 }
340 
341 /// indent - Insert 'NumSpaces' spaces.
342 raw_ostream &raw_ostream::indent(unsigned NumSpaces) {
343   static const char Spaces[] = "                                "
344                                "                                "
345                                "                ";
346 
347   // Usually the indentation is small, handle it with a fastpath.
348   if (NumSpaces < array_lengthof(Spaces))
349     return write(Spaces, NumSpaces);
350 
351   while (NumSpaces) {
352     unsigned NumToWrite = std::min(NumSpaces,
353                                    (unsigned)array_lengthof(Spaces)-1);
354     write(Spaces, NumToWrite);
355     NumSpaces -= NumToWrite;
356   }
357   return *this;
358 }
359 
360 //===----------------------------------------------------------------------===//
361 //  Formatted Output
362 //===----------------------------------------------------------------------===//
363 
364 // Out of line virtual method.
365 void format_object_base::home() {
366 }
367 
368 //===----------------------------------------------------------------------===//
369 //  raw_fd_ostream
370 //===----------------------------------------------------------------------===//
371 
372 static int getFD(StringRef Filename, std::error_code &EC,
373                  sys::fs::OpenFlags Flags) {
374   // Handle "-" as stdout. Note that when we do this, we consider ourself
375   // the owner of stdout. This means that we can do things like close the
376   // file descriptor when we're done and set the "binary" flag globally.
377   if (Filename == "-") {
378     EC = std::error_code();
379     // If user requested binary then put stdout into binary mode if
380     // possible.
381     if (!(Flags & sys::fs::F_Text))
382       sys::ChangeStdoutToBinary();
383     return STDOUT_FILENO;
384   }
385 
386   int FD;
387   EC = sys::fs::openFileForWrite(Filename, FD, Flags);
388   if (EC)
389     return -1;
390 
391   return FD;
392 }
393 
394 raw_fd_ostream::raw_fd_ostream(StringRef Filename, std::error_code &EC,
395                                sys::fs::OpenFlags Flags)
396     : raw_fd_ostream(getFD(Filename, EC, Flags), true) {}
397 
398 /// FD is the file descriptor that this writes to.  If ShouldClose is true, this
399 /// closes the file when the stream is destroyed.
400 raw_fd_ostream::raw_fd_ostream(int fd, bool shouldClose, bool unbuffered)
401     : raw_pwrite_stream(unbuffered), FD(fd), ShouldClose(shouldClose),
402       Error(false) {
403   if (FD < 0 ) {
404     ShouldClose = false;
405     return;
406   }
407 
408   // Get the starting position.
409   off_t loc = ::lseek(FD, 0, SEEK_CUR);
410 #ifdef LLVM_ON_WIN32
411   // MSVCRT's _lseek(SEEK_CUR) doesn't return -1 for pipes.
412   sys::fs::file_status Status;
413   std::error_code EC = status(FD, Status);
414   SupportsSeeking = !EC && Status.type() == sys::fs::file_type::regular_file;
415 #else
416   SupportsSeeking = loc != (off_t)-1;
417 #endif
418   if (!SupportsSeeking)
419     pos = 0;
420   else
421     pos = static_cast<uint64_t>(loc);
422 }
423 
424 raw_fd_ostream::~raw_fd_ostream() {
425   if (FD >= 0) {
426     flush();
427     if (ShouldClose && sys::Process::SafelyCloseFileDescriptor(FD))
428       error_detected();
429   }
430 
431 #ifdef __MINGW32__
432   // On mingw, global dtors should not call exit().
433   // report_fatal_error() invokes exit(). We know report_fatal_error()
434   // might not write messages to stderr when any errors were detected
435   // on FD == 2.
436   if (FD == 2) return;
437 #endif
438 
439   // If there are any pending errors, report them now. Clients wishing
440   // to avoid report_fatal_error calls should check for errors with
441   // has_error() and clear the error flag with clear_error() before
442   // destructing raw_ostream objects which may have errors.
443   if (has_error())
444     report_fatal_error("IO failure on output stream.", /*GenCrashDiag=*/false);
445 }
446 
447 void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) {
448   assert(FD >= 0 && "File already closed.");
449   pos += Size;
450 
451 #ifndef LLVM_ON_WIN32
452   bool ShouldWriteInChunks = false;
453 #else
454   // Writing a large size of output to Windows console returns ENOMEM. It seems
455   // that, prior to Windows 8, WriteFile() is redirecting to WriteConsole(), and
456   // the latter has a size limit (66000 bytes or less, depending on heap usage).
457   bool ShouldWriteInChunks = !!::_isatty(FD) && !RunningWindows8OrGreater();
458 #endif
459 
460   do {
461     size_t ChunkSize = Size;
462     if (ChunkSize > 32767 && ShouldWriteInChunks)
463         ChunkSize = 32767;
464 
465     ssize_t ret = ::write(FD, Ptr, ChunkSize);
466 
467     if (ret < 0) {
468       // If it's a recoverable error, swallow it and retry the write.
469       //
470       // Ideally we wouldn't ever see EAGAIN or EWOULDBLOCK here, since
471       // raw_ostream isn't designed to do non-blocking I/O. However, some
472       // programs, such as old versions of bjam, have mistakenly used
473       // O_NONBLOCK. For compatibility, emulate blocking semantics by
474       // spinning until the write succeeds. If you don't want spinning,
475       // don't use O_NONBLOCK file descriptors with raw_ostream.
476       if (errno == EINTR || errno == EAGAIN
477 #ifdef EWOULDBLOCK
478           || errno == EWOULDBLOCK
479 #endif
480           )
481         continue;
482 
483       // Otherwise it's a non-recoverable error. Note it and quit.
484       error_detected();
485       break;
486     }
487 
488     // The write may have written some or all of the data. Update the
489     // size and buffer pointer to reflect the remainder that needs
490     // to be written. If there are no bytes left, we're done.
491     Ptr += ret;
492     Size -= ret;
493   } while (Size > 0);
494 }
495 
496 void raw_fd_ostream::close() {
497   assert(ShouldClose);
498   ShouldClose = false;
499   flush();
500   if (sys::Process::SafelyCloseFileDescriptor(FD))
501     error_detected();
502   FD = -1;
503 }
504 
505 uint64_t raw_fd_ostream::seek(uint64_t off) {
506   assert(SupportsSeeking && "Stream does not support seeking!");
507   flush();
508   pos = ::lseek(FD, off, SEEK_SET);
509   if (pos == (uint64_t)-1)
510     error_detected();
511   return pos;
512 }
513 
514 void raw_fd_ostream::pwrite_impl(const char *Ptr, size_t Size,
515                                  uint64_t Offset) {
516   uint64_t Pos = tell();
517   seek(Offset);
518   write(Ptr, Size);
519   seek(Pos);
520 }
521 
522 size_t raw_fd_ostream::preferred_buffer_size() const {
523 #if !defined(_MSC_VER) && !defined(__MINGW32__) && !defined(__minix)
524   // Windows and Minix have no st_blksize.
525   assert(FD >= 0 && "File not yet open!");
526   struct stat statbuf;
527   if (fstat(FD, &statbuf) != 0)
528     return 0;
529 
530   // If this is a terminal, don't use buffering. Line buffering
531   // would be a more traditional thing to do, but it's not worth
532   // the complexity.
533   if (S_ISCHR(statbuf.st_mode) && isatty(FD))
534     return 0;
535   // Return the preferred block size.
536   return statbuf.st_blksize;
537 #else
538   return raw_ostream::preferred_buffer_size();
539 #endif
540 }
541 
542 raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold,
543                                          bool bg) {
544   if (sys::Process::ColorNeedsFlush())
545     flush();
546   const char *colorcode =
547     (colors == SAVEDCOLOR) ? sys::Process::OutputBold(bg)
548     : sys::Process::OutputColor(colors, bold, bg);
549   if (colorcode) {
550     size_t len = strlen(colorcode);
551     write(colorcode, len);
552     // don't account colors towards output characters
553     pos -= len;
554   }
555   return *this;
556 }
557 
558 raw_ostream &raw_fd_ostream::resetColor() {
559   if (sys::Process::ColorNeedsFlush())
560     flush();
561   const char *colorcode = sys::Process::ResetColor();
562   if (colorcode) {
563     size_t len = strlen(colorcode);
564     write(colorcode, len);
565     // don't account colors towards output characters
566     pos -= len;
567   }
568   return *this;
569 }
570 
571 raw_ostream &raw_fd_ostream::reverseColor() {
572   if (sys::Process::ColorNeedsFlush())
573     flush();
574   const char *colorcode = sys::Process::OutputReverse();
575   if (colorcode) {
576     size_t len = strlen(colorcode);
577     write(colorcode, len);
578     // don't account colors towards output characters
579     pos -= len;
580   }
581   return *this;
582 }
583 
584 bool raw_fd_ostream::is_displayed() const {
585   return sys::Process::FileDescriptorIsDisplayed(FD);
586 }
587 
588 bool raw_fd_ostream::has_colors() const {
589   return sys::Process::FileDescriptorHasColors(FD);
590 }
591 
592 //===----------------------------------------------------------------------===//
593 //  outs(), errs(), nulls()
594 //===----------------------------------------------------------------------===//
595 
596 /// outs() - This returns a reference to a raw_ostream for standard output.
597 /// Use it like: outs() << "foo" << "bar";
598 raw_ostream &llvm::outs() {
599   // Set buffer settings to model stdout behavior.  Delete the file descriptor
600   // when the program exits, forcing error detection.  This means that if you
601   // ever call outs(), you can't open another raw_fd_ostream on stdout, as we'll
602   // close stdout twice and print an error the second time.
603   std::error_code EC;
604   static raw_fd_ostream S("-", EC, sys::fs::F_None);
605   assert(!EC);
606   return S;
607 }
608 
609 /// errs() - This returns a reference to a raw_ostream for standard error.
610 /// Use it like: errs() << "foo" << "bar";
611 raw_ostream &llvm::errs() {
612   // Set standard error to be unbuffered by default.
613   static raw_fd_ostream S(STDERR_FILENO, false, true);
614   return S;
615 }
616 
617 /// nulls() - This returns a reference to a raw_ostream which discards output.
618 raw_ostream &llvm::nulls() {
619   static raw_null_ostream S;
620   return S;
621 }
622 
623 //===----------------------------------------------------------------------===//
624 //  raw_string_ostream
625 //===----------------------------------------------------------------------===//
626 
627 raw_string_ostream::~raw_string_ostream() {
628   flush();
629 }
630 
631 void raw_string_ostream::write_impl(const char *Ptr, size_t Size) {
632   OS.append(Ptr, Size);
633 }
634 
635 //===----------------------------------------------------------------------===//
636 //  raw_svector_ostream
637 //===----------------------------------------------------------------------===//
638 
639 uint64_t raw_svector_ostream::current_pos() const { return OS.size(); }
640 
641 void raw_svector_ostream::write_impl(const char *Ptr, size_t Size) {
642   OS.append(Ptr, Ptr + Size);
643 }
644 
645 void raw_svector_ostream::pwrite_impl(const char *Ptr, size_t Size,
646                                       uint64_t Offset) {
647   memcpy(OS.data() + Offset, Ptr, Size);
648 }
649 
650 //===----------------------------------------------------------------------===//
651 //  raw_null_ostream
652 //===----------------------------------------------------------------------===//
653 
654 raw_null_ostream::~raw_null_ostream() {
655 #ifndef NDEBUG
656   // ~raw_ostream asserts that the buffer is empty. This isn't necessary
657   // with raw_null_ostream, but it's better to have raw_null_ostream follow
658   // the rules than to change the rules just for raw_null_ostream.
659   flush();
660 #endif
661 }
662 
663 void raw_null_ostream::write_impl(const char *Ptr, size_t Size) {
664 }
665 
666 uint64_t raw_null_ostream::current_pos() const {
667   return 0;
668 }
669 
670 void raw_null_ostream::pwrite_impl(const char *Ptr, size_t Size,
671                                    uint64_t Offset) {}
672