Handle EWOULDBLOCK as EAGAIN. And add a comment explaining why
[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     N = -N;
149   }
150
151   return this->operator<<(static_cast<unsigned long long>(N));
152 }
153
154 raw_ostream &raw_ostream::write_hex(unsigned long long N) {
155   // Zero is a special case.
156   if (N == 0)
157     return *this << '0';
158
159   char NumberBuffer[20];
160   char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
161   char *CurPtr = EndPtr;
162
163   while (N) {
164     uintptr_t x = N % 16;
165     *--CurPtr = (x < 10 ? '0' + x : 'a' + x - 10);
166     N /= 16;
167   }
168
169   return write(CurPtr, EndPtr-CurPtr);
170 }
171
172 raw_ostream &raw_ostream::write_escaped(StringRef Str) {
173   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
174     unsigned char c = Str[i];
175
176     switch (c) {
177     case '\\':
178       *this << '\\' << '\\';
179       break;
180     case '\t':
181       *this << '\\' << 't';
182       break;
183     case '\n':
184       *this << '\\' << 'n';
185       break;
186     case '"':
187       *this << '\\' << '"';
188       break;
189     default:
190       if (std::isprint(c)) {
191         *this << c;
192         break;
193       }
194
195       // Always expand to a 3-character octal escape.
196       *this << '\\';
197       *this << char('0' + ((c >> 6) & 7));
198       *this << char('0' + ((c >> 3) & 7));
199       *this << char('0' + ((c >> 0) & 7));
200     }
201   }
202
203   return *this;
204 }
205
206 raw_ostream &raw_ostream::operator<<(const void *P) {
207   *this << '0' << 'x';
208
209   return write_hex((uintptr_t) P);
210 }
211
212 raw_ostream &raw_ostream::operator<<(double N) {
213   return this->operator<<(format("%e", N));
214 }
215
216
217
218 void raw_ostream::flush_nonempty() {
219   assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty.");
220   size_t Length = OutBufCur - OutBufStart;
221   OutBufCur = OutBufStart;
222   write_impl(OutBufStart, Length);
223 }
224
225 raw_ostream &raw_ostream::write(unsigned char C) {
226   // Group exceptional cases into a single branch.
227   if (BUILTIN_EXPECT(OutBufCur >= OutBufEnd, false)) {
228     if (BUILTIN_EXPECT(!OutBufStart, false)) {
229       if (BufferMode == Unbuffered) {
230         write_impl(reinterpret_cast<char*>(&C), 1);
231         return *this;
232       }
233       // Set up a buffer and start over.
234       SetBuffered();
235       return write(C);
236     }
237
238     flush_nonempty();
239   }
240
241   *OutBufCur++ = C;
242   return *this;
243 }
244
245 raw_ostream &raw_ostream::write(const char *Ptr, size_t Size) {
246   // Group exceptional cases into a single branch.
247   if (BUILTIN_EXPECT(OutBufCur+Size > OutBufEnd, false)) {
248     if (BUILTIN_EXPECT(!OutBufStart, false)) {
249       if (BufferMode == Unbuffered) {
250         write_impl(Ptr, Size);
251         return *this;
252       }
253       // Set up a buffer and start over.
254       SetBuffered();
255       return write(Ptr, Size);
256     }
257
258     // Write out the data in buffer-sized blocks until the remainder
259     // fits within the buffer.
260     do {
261       size_t NumBytes = OutBufEnd - OutBufCur;
262       copy_to_buffer(Ptr, NumBytes);
263       flush_nonempty();
264       Ptr += NumBytes;
265       Size -= NumBytes;
266     } while (OutBufCur+Size > OutBufEnd);
267   }
268
269   copy_to_buffer(Ptr, Size);
270
271   return *this;
272 }
273
274 void raw_ostream::copy_to_buffer(const char *Ptr, size_t Size) {
275   assert(Size <= size_t(OutBufEnd - OutBufCur) && "Buffer overrun!");
276
277   // Handle short strings specially, memcpy isn't very good at very short
278   // strings.
279   switch (Size) {
280   case 4: OutBufCur[3] = Ptr[3]; // FALL THROUGH
281   case 3: OutBufCur[2] = Ptr[2]; // FALL THROUGH
282   case 2: OutBufCur[1] = Ptr[1]; // FALL THROUGH
283   case 1: OutBufCur[0] = Ptr[0]; // FALL THROUGH
284   case 0: break;
285   default:
286     memcpy(OutBufCur, Ptr, Size);
287     break;
288   }
289
290   OutBufCur += Size;
291 }
292
293 // Formatted output.
294 raw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) {
295   // If we have more than a few bytes left in our output buffer, try
296   // formatting directly onto its end.
297   size_t NextBufferSize = 127;
298   size_t BufferBytesLeft = OutBufEnd - OutBufCur;
299   if (BufferBytesLeft > 3) {
300     size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft);
301
302     // Common case is that we have plenty of space.
303     if (BytesUsed <= BufferBytesLeft) {
304       OutBufCur += BytesUsed;
305       return *this;
306     }
307
308     // Otherwise, we overflowed and the return value tells us the size to try
309     // again with.
310     NextBufferSize = BytesUsed;
311   }
312
313   // If we got here, we didn't have enough space in the output buffer for the
314   // string.  Try printing into a SmallVector that is resized to have enough
315   // space.  Iterate until we win.
316   SmallVector<char, 128> V;
317
318   while (1) {
319     V.resize(NextBufferSize);
320
321     // Try formatting into the SmallVector.
322     size_t BytesUsed = Fmt.print(V.data(), NextBufferSize);
323
324     // If BytesUsed fit into the vector, we win.
325     if (BytesUsed <= NextBufferSize)
326       return write(V.data(), BytesUsed);
327
328     // Otherwise, try again with a new size.
329     assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?");
330     NextBufferSize = BytesUsed;
331   }
332 }
333
334 /// indent - Insert 'NumSpaces' spaces.
335 raw_ostream &raw_ostream::indent(unsigned NumSpaces) {
336   static const char Spaces[] = "                                "
337                                "                                "
338                                "                ";
339
340   // Usually the indentation is small, handle it with a fastpath.
341   if (NumSpaces < array_lengthof(Spaces))
342     return write(Spaces, NumSpaces);
343
344   while (NumSpaces) {
345     unsigned NumToWrite = std::min(NumSpaces,
346                                    (unsigned)array_lengthof(Spaces)-1);
347     write(Spaces, NumToWrite);
348     NumSpaces -= NumToWrite;
349   }
350   return *this;
351 }
352
353
354 //===----------------------------------------------------------------------===//
355 //  Formatted Output
356 //===----------------------------------------------------------------------===//
357
358 // Out of line virtual method.
359 void format_object_base::home() {
360 }
361
362 //===----------------------------------------------------------------------===//
363 //  raw_fd_ostream
364 //===----------------------------------------------------------------------===//
365
366 /// raw_fd_ostream - Open the specified file for writing. If an error
367 /// occurs, information about the error is put into ErrorInfo, and the
368 /// stream should be immediately destroyed; the string will be empty
369 /// if no error occurred.
370 raw_fd_ostream::raw_fd_ostream(const char *Filename, std::string &ErrorInfo,
371                                unsigned Flags) : pos(0) {
372   assert(Filename != 0 && "Filename is null");
373   // Verify that we don't have both "append" and "excl".
374   assert((!(Flags & F_Excl) || !(Flags & F_Append)) &&
375          "Cannot specify both 'excl' and 'append' file creation flags!");
376
377   ErrorInfo.clear();
378
379   // Handle "-" as stdout.
380   if (Filename[0] == '-' && Filename[1] == 0) {
381     FD = STDOUT_FILENO;
382     // If user requested binary then put stdout into binary mode if
383     // possible.
384     if (Flags & F_Binary)
385       sys::Program::ChangeStdoutToBinary();
386     ShouldClose = false;
387     return;
388   }
389
390   int OpenFlags = O_WRONLY|O_CREAT;
391 #ifdef O_BINARY
392   if (Flags & F_Binary)
393     OpenFlags |= O_BINARY;
394 #endif
395
396   if (Flags & F_Append)
397     OpenFlags |= O_APPEND;
398   else
399     OpenFlags |= O_TRUNC;
400   if (Flags & F_Excl)
401     OpenFlags |= O_EXCL;
402
403   FD = open(Filename, OpenFlags, 0664);
404   if (FD < 0) {
405     ErrorInfo = "Error opening output file '" + std::string(Filename) + "'";
406     ShouldClose = false;
407   } else {
408     ShouldClose = true;
409   }
410 }
411
412 raw_fd_ostream::~raw_fd_ostream() {
413   if (FD < 0) return;
414   flush();
415   if (ShouldClose)
416     if (::close(FD) != 0)
417       error_detected();
418 }
419
420
421 void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) {
422   assert(FD >= 0 && "File already closed.");
423   pos += Size;
424   ssize_t ret;
425
426   do {
427     ret = ::write(FD, Ptr, Size);
428
429     if (ret < 0) {
430       // If it's a recoverable error, swallow it and retry the write.
431       // EAGAIN and EWOULDBLOCK are not unambiguously recoverable, but
432       // some programs, such as bjam, assume that their child processes
433       // will treat them as if they are. If you don't want this code to
434       // spin, don't use O_NONBLOCK file descriptors with raw_ostream.
435       if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK)
436         continue;
437
438       // Otherwise it's a non-recoverable error. Note it and quit.
439       error_detected();
440       break;
441     }
442
443     // The write may have written some or all of the data. Update the
444     // size and buffer pointer to reflect the remainder that needs
445     // to be written. If there are no bytes left, we're done.
446     Ptr += ret;
447     Size -= ret;
448   } while (Size > 0);
449 }
450
451 void raw_fd_ostream::close() {
452   assert(ShouldClose);
453   ShouldClose = false;
454   flush();
455   if (::close(FD) != 0)
456     error_detected();
457   FD = -1;
458 }
459
460 uint64_t raw_fd_ostream::seek(uint64_t off) {
461   flush();
462   pos = ::lseek(FD, off, SEEK_SET);
463   if (pos != off)
464     error_detected();
465   return pos;
466 }
467
468 size_t raw_fd_ostream::preferred_buffer_size() const {
469 #if !defined(_MSC_VER) && !defined(__MINGW32__) && !defined(_MINIX)
470   // Windows and Minix have no st_blksize.
471   assert(FD >= 0 && "File not yet open!");
472   struct stat statbuf;
473   if (fstat(FD, &statbuf) != 0)
474     return 0;
475
476   // If this is a terminal, don't use buffering. Line buffering
477   // would be a more traditional thing to do, but it's not worth
478   // the complexity.
479   if (S_ISCHR(statbuf.st_mode) && isatty(FD))
480     return 0;
481   // Return the preferred block size.
482   return statbuf.st_blksize;
483 #endif
484   return raw_ostream::preferred_buffer_size();
485 }
486
487 raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold,
488                                          bool bg) {
489   if (sys::Process::ColorNeedsFlush())
490     flush();
491   const char *colorcode =
492     (colors == SAVEDCOLOR) ? sys::Process::OutputBold(bg)
493     : sys::Process::OutputColor(colors, bold, bg);
494   if (colorcode) {
495     size_t len = strlen(colorcode);
496     write(colorcode, len);
497     // don't account colors towards output characters
498     pos -= len;
499   }
500   return *this;
501 }
502
503 raw_ostream &raw_fd_ostream::resetColor() {
504   if (sys::Process::ColorNeedsFlush())
505     flush();
506   const char *colorcode = sys::Process::ResetColor();
507   if (colorcode) {
508     size_t len = strlen(colorcode);
509     write(colorcode, len);
510     // don't account colors towards output characters
511     pos -= len;
512   }
513   return *this;
514 }
515
516 bool raw_fd_ostream::is_displayed() const {
517   return sys::Process::FileDescriptorIsDisplayed(FD);
518 }
519
520 //===----------------------------------------------------------------------===//
521 //  raw_stdout/err_ostream
522 //===----------------------------------------------------------------------===//
523
524 // Set buffer settings to model stdout and stderr behavior.
525 // Set standard error to be unbuffered by default.
526 raw_stdout_ostream::raw_stdout_ostream():raw_fd_ostream(STDOUT_FILENO, false) {}
527 raw_stderr_ostream::raw_stderr_ostream():raw_fd_ostream(STDERR_FILENO, false,
528                                                         true) {}
529
530 // An out of line virtual method to provide a home for the class vtable.
531 void raw_stdout_ostream::handle() {}
532 void raw_stderr_ostream::handle() {}
533
534 /// outs() - This returns a reference to a raw_ostream for standard output.
535 /// Use it like: outs() << "foo" << "bar";
536 raw_ostream &llvm::outs() {
537   static raw_stdout_ostream S;
538   return S;
539 }
540
541 /// errs() - This returns a reference to a raw_ostream for standard error.
542 /// Use it like: errs() << "foo" << "bar";
543 raw_ostream &llvm::errs() {
544   static raw_stderr_ostream S;
545   return S;
546 }
547
548 /// nulls() - This returns a reference to a raw_ostream which discards output.
549 raw_ostream &llvm::nulls() {
550   static raw_null_ostream S;
551   return S;
552 }
553
554
555 //===----------------------------------------------------------------------===//
556 //  raw_string_ostream
557 //===----------------------------------------------------------------------===//
558
559 raw_string_ostream::~raw_string_ostream() {
560   flush();
561 }
562
563 void raw_string_ostream::write_impl(const char *Ptr, size_t Size) {
564   OS.append(Ptr, Size);
565 }
566
567 //===----------------------------------------------------------------------===//
568 //  raw_svector_ostream
569 //===----------------------------------------------------------------------===//
570
571 // The raw_svector_ostream implementation uses the SmallVector itself as the
572 // buffer for the raw_ostream. We guarantee that the raw_ostream buffer is
573 // always pointing past the end of the vector, but within the vector
574 // capacity. This allows raw_ostream to write directly into the correct place,
575 // and we only need to set the vector size when the data is flushed.
576
577 raw_svector_ostream::raw_svector_ostream(SmallVectorImpl<char> &O) : OS(O) {
578   // Set up the initial external buffer. We make sure that the buffer has at
579   // least 128 bytes free; raw_ostream itself only requires 64, but we want to
580   // make sure that we don't grow the buffer unnecessarily on destruction (when
581   // the data is flushed). See the FIXME below.
582   OS.reserve(OS.size() + 128);
583   SetBuffer(OS.end(), OS.capacity() - OS.size());
584 }
585
586 raw_svector_ostream::~raw_svector_ostream() {
587   // FIXME: Prevent resizing during this flush().
588   flush();
589 }
590
591 /// resync - This is called when the SmallVector we're appending to is changed
592 /// outside of the raw_svector_ostream's control.  It is only safe to do this
593 /// if the raw_svector_ostream has previously been flushed.
594 void raw_svector_ostream::resync() {
595   assert(GetNumBytesInBuffer() == 0 && "Didn't flush before mutating vector");
596
597   if (OS.capacity() - OS.size() < 64)
598     OS.reserve(OS.capacity() * 2);
599   SetBuffer(OS.end(), OS.capacity() - OS.size());
600 }
601
602 void raw_svector_ostream::write_impl(const char *Ptr, size_t Size) {
603   // If we're writing bytes from the end of the buffer into the smallvector, we
604   // don't need to copy the bytes, just commit the bytes because they are
605   // already in the right place.
606   if (Ptr == OS.end()) {
607     assert(OS.size() + Size <= OS.capacity() && "Invalid write_impl() call!");
608     OS.set_size(OS.size() + Size);
609   } else {
610     assert(GetNumBytesInBuffer() == 0 &&
611            "Should be writing from buffer if some bytes in it");
612     // Otherwise, do copy the bytes.
613     OS.append(Ptr, Ptr+Size);
614   }
615
616   // Grow the vector if necessary.
617   if (OS.capacity() - OS.size() < 64)
618     OS.reserve(OS.capacity() * 2);
619
620   // Update the buffer position.
621   SetBuffer(OS.end(), OS.capacity() - OS.size());
622 }
623
624 uint64_t raw_svector_ostream::current_pos() const {
625    return OS.size();
626 }
627
628 StringRef raw_svector_ostream::str() {
629   flush();
630   return StringRef(OS.begin(), OS.size());
631 }
632
633 //===----------------------------------------------------------------------===//
634 //  raw_null_ostream
635 //===----------------------------------------------------------------------===//
636
637 raw_null_ostream::~raw_null_ostream() {
638 #ifndef NDEBUG
639   // ~raw_ostream asserts that the buffer is empty. This isn't necessary
640   // with raw_null_ostream, but it's better to have raw_null_ostream follow
641   // the rules than to change the rules just for raw_null_ostream.
642   flush();
643 #endif
644 }
645
646 void raw_null_ostream::write_impl(const char *Ptr, size_t Size) {
647 }
648
649 uint64_t raw_null_ostream::current_pos() const {
650   return 0;
651 }