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