Introduce a new tool_output_file class, which extends raw_ostream with
[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/System/Signals.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include <cctype>
25 #include <cerrno>
26 #include <sys/stat.h>
27 #include <sys/types.h>
28
29 #if defined(HAVE_UNISTD_H)
30 # include <unistd.h>
31 #endif
32 #if defined(HAVE_FCNTL_H)
33 # include <fcntl.h>
34 #endif
35
36 #if defined(_MSC_VER)
37 #include <io.h>
38 #include <fcntl.h>
39 #ifndef STDIN_FILENO
40 # define STDIN_FILENO 0
41 #endif
42 #ifndef STDOUT_FILENO
43 # define STDOUT_FILENO 1
44 #endif
45 #ifndef STDERR_FILENO
46 # define STDERR_FILENO 2
47 #endif
48 #endif
49
50 using namespace llvm;
51
52 raw_ostream::~raw_ostream() {
53   // raw_ostream's subclasses should take care to flush the buffer
54   // in their destructors.
55   assert(OutBufCur == OutBufStart &&
56          "raw_ostream destructor called with non-empty buffer!");
57
58   if (BufferMode == InternalBuffer)
59     delete [] OutBufStart;
60
61   // If there are any pending errors, report them now. Clients wishing
62   // to avoid report_fatal_error calls should check for errors with
63   // has_error() and clear the error flag with clear_error() before
64   // destructing raw_ostream objects which may have errors.
65   if (Error)
66     report_fatal_error("IO failure on output stream.");
67 }
68
69 // An out of line virtual method to provide a home for the class vtable.
70 void raw_ostream::handle() {}
71
72 size_t raw_ostream::preferred_buffer_size() const {
73   // BUFSIZ is intended to be a reasonable default.
74   return BUFSIZ;
75 }
76
77 void raw_ostream::SetBuffered() {
78   // Ask the subclass to determine an appropriate buffer size.
79   if (size_t Size = preferred_buffer_size())
80     SetBufferSize(Size);
81   else
82     // It may return 0, meaning this stream should be unbuffered.
83     SetUnbuffered();
84 }
85
86 void raw_ostream::SetBufferAndMode(char *BufferStart, size_t Size,
87                                     BufferKind Mode) {
88   assert(((Mode == Unbuffered && BufferStart == 0 && Size == 0) ||
89           (Mode != Unbuffered && BufferStart && Size)) &&
90          "stream must be unbuffered or have at least one byte");
91   // Make sure the current buffer is free of content (we can't flush here; the
92   // child buffer management logic will be in write_impl).
93   assert(GetNumBytesInBuffer() == 0 && "Current buffer is non-empty!");
94
95   if (BufferMode == InternalBuffer)
96     delete [] OutBufStart;
97   OutBufStart = BufferStart;
98   OutBufEnd = OutBufStart+Size;
99   OutBufCur = OutBufStart;
100   BufferMode = Mode;
101
102   assert(OutBufStart <= OutBufEnd && "Invalid size!");
103 }
104
105 raw_ostream &raw_ostream::operator<<(unsigned long N) {
106   // Zero is a special case.
107   if (N == 0)
108     return *this << '0';
109
110   char NumberBuffer[20];
111   char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
112   char *CurPtr = EndPtr;
113
114   while (N) {
115     *--CurPtr = '0' + char(N % 10);
116     N /= 10;
117   }
118   return write(CurPtr, EndPtr-CurPtr);
119 }
120
121 raw_ostream &raw_ostream::operator<<(long N) {
122   if (N <  0) {
123     *this << '-';
124     N = -N;
125   }
126
127   return this->operator<<(static_cast<unsigned long>(N));
128 }
129
130 raw_ostream &raw_ostream::operator<<(unsigned long long N) {
131   // Output using 32-bit div/mod when possible.
132   if (N == static_cast<unsigned long>(N))
133     return this->operator<<(static_cast<unsigned long>(N));
134
135   char NumberBuffer[20];
136   char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
137   char *CurPtr = EndPtr;
138
139   while (N) {
140     *--CurPtr = '0' + char(N % 10);
141     N /= 10;
142   }
143   return write(CurPtr, EndPtr-CurPtr);
144 }
145
146 raw_ostream &raw_ostream::operator<<(long long N) {
147   if (N < 0) {
148     *this << '-';
149     // Avoid undefined behavior on INT64_MIN with a cast.
150     N = -(unsigned long long)N;
151   }
152
153   return this->operator<<(static_cast<unsigned long long>(N));
154 }
155
156 raw_ostream &raw_ostream::write_hex(unsigned long long N) {
157   // Zero is a special case.
158   if (N == 0)
159     return *this << '0';
160
161   char NumberBuffer[20];
162   char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
163   char *CurPtr = EndPtr;
164
165   while (N) {
166     uintptr_t x = N % 16;
167     *--CurPtr = (x < 10 ? '0' + x : 'a' + x - 10);
168     N /= 16;
169   }
170
171   return write(CurPtr, EndPtr-CurPtr);
172 }
173
174 raw_ostream &raw_ostream::write_escaped(StringRef Str) {
175   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
176     unsigned char c = Str[i];
177
178     switch (c) {
179     case '\\':
180       *this << '\\' << '\\';
181       break;
182     case '\t':
183       *this << '\\' << 't';
184       break;
185     case '\n':
186       *this << '\\' << 'n';
187       break;
188     case '"':
189       *this << '\\' << '"';
190       break;
191     default:
192       if (std::isprint(c)) {
193         *this << c;
194         break;
195       }
196
197       // Always expand to a 3-character octal escape.
198       *this << '\\';
199       *this << char('0' + ((c >> 6) & 7));
200       *this << char('0' + ((c >> 3) & 7));
201       *this << char('0' + ((c >> 0) & 7));
202     }
203   }
204
205   return *this;
206 }
207
208 raw_ostream &raw_ostream::operator<<(const void *P) {
209   *this << '0' << 'x';
210
211   return write_hex((uintptr_t) P);
212 }
213
214 raw_ostream &raw_ostream::operator<<(double N) {
215   return this->operator<<(format("%e", N));
216 }
217
218
219
220 void raw_ostream::flush_nonempty() {
221   assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty.");
222   size_t Length = OutBufCur - OutBufStart;
223   OutBufCur = OutBufStart;
224   write_impl(OutBufStart, Length);
225 }
226
227 raw_ostream &raw_ostream::write(unsigned char C) {
228   // Group exceptional cases into a single branch.
229   if (BUILTIN_EXPECT(OutBufCur >= OutBufEnd, false)) {
230     if (BUILTIN_EXPECT(!OutBufStart, false)) {
231       if (BufferMode == Unbuffered) {
232         write_impl(reinterpret_cast<char*>(&C), 1);
233         return *this;
234       }
235       // Set up a buffer and start over.
236       SetBuffered();
237       return write(C);
238     }
239
240     flush_nonempty();
241   }
242
243   *OutBufCur++ = C;
244   return *this;
245 }
246
247 raw_ostream &raw_ostream::write(const char *Ptr, size_t Size) {
248   // Group exceptional cases into a single branch.
249   if (BUILTIN_EXPECT(OutBufCur+Size > OutBufEnd, false)) {
250     if (BUILTIN_EXPECT(!OutBufStart, false)) {
251       if (BufferMode == Unbuffered) {
252         write_impl(Ptr, Size);
253         return *this;
254       }
255       // Set up a buffer and start over.
256       SetBuffered();
257       return write(Ptr, Size);
258     }
259
260     // Write out the data in buffer-sized blocks until the remainder
261     // fits within the buffer.
262     do {
263       size_t NumBytes = OutBufEnd - OutBufCur;
264       copy_to_buffer(Ptr, NumBytes);
265       flush_nonempty();
266       Ptr += NumBytes;
267       Size -= NumBytes;
268     } while (OutBufCur+Size > OutBufEnd);
269   }
270
271   copy_to_buffer(Ptr, Size);
272
273   return *this;
274 }
275
276 void raw_ostream::copy_to_buffer(const char *Ptr, size_t Size) {
277   assert(Size <= size_t(OutBufEnd - OutBufCur) && "Buffer overrun!");
278
279   // Handle short strings specially, memcpy isn't very good at very short
280   // strings.
281   switch (Size) {
282   case 4: OutBufCur[3] = Ptr[3]; // FALL THROUGH
283   case 3: OutBufCur[2] = Ptr[2]; // FALL THROUGH
284   case 2: OutBufCur[1] = Ptr[1]; // FALL THROUGH
285   case 1: OutBufCur[0] = Ptr[0]; // FALL THROUGH
286   case 0: break;
287   default:
288     memcpy(OutBufCur, Ptr, Size);
289     break;
290   }
291
292   OutBufCur += Size;
293 }
294
295 // Formatted output.
296 raw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) {
297   // If we have more than a few bytes left in our output buffer, try
298   // formatting directly onto its end.
299   size_t NextBufferSize = 127;
300   size_t BufferBytesLeft = OutBufEnd - OutBufCur;
301   if (BufferBytesLeft > 3) {
302     size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft);
303
304     // Common case is that we have plenty of space.
305     if (BytesUsed <= BufferBytesLeft) {
306       OutBufCur += BytesUsed;
307       return *this;
308     }
309
310     // Otherwise, we overflowed and the return value tells us the size to try
311     // again with.
312     NextBufferSize = BytesUsed;
313   }
314
315   // If we got here, we didn't have enough space in the output buffer for the
316   // string.  Try printing into a SmallVector that is resized to have enough
317   // space.  Iterate until we win.
318   SmallVector<char, 128> V;
319
320   while (1) {
321     V.resize(NextBufferSize);
322
323     // Try formatting into the SmallVector.
324     size_t BytesUsed = Fmt.print(V.data(), NextBufferSize);
325
326     // If BytesUsed fit into the vector, we win.
327     if (BytesUsed <= NextBufferSize)
328       return write(V.data(), BytesUsed);
329
330     // Otherwise, try again with a new size.
331     assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?");
332     NextBufferSize = BytesUsed;
333   }
334 }
335
336 /// indent - Insert 'NumSpaces' spaces.
337 raw_ostream &raw_ostream::indent(unsigned NumSpaces) {
338   static const char Spaces[] = "                                "
339                                "                                "
340                                "                ";
341
342   // Usually the indentation is small, handle it with a fastpath.
343   if (NumSpaces < array_lengthof(Spaces))
344     return write(Spaces, NumSpaces);
345
346   while (NumSpaces) {
347     unsigned NumToWrite = std::min(NumSpaces,
348                                    (unsigned)array_lengthof(Spaces)-1);
349     write(Spaces, NumToWrite);
350     NumSpaces -= NumToWrite;
351   }
352   return *this;
353 }
354
355
356 //===----------------------------------------------------------------------===//
357 //  Formatted Output
358 //===----------------------------------------------------------------------===//
359
360 // Out of line virtual method.
361 void format_object_base::home() {
362 }
363
364 //===----------------------------------------------------------------------===//
365 //  raw_fd_ostream
366 //===----------------------------------------------------------------------===//
367
368 /// raw_fd_ostream - Open the specified file for writing. If an error
369 /// occurs, information about the error is put into ErrorInfo, and the
370 /// stream should be immediately destroyed; the string will be empty
371 /// if no error occurred.
372 raw_fd_ostream::raw_fd_ostream(const char *Filename, std::string &ErrorInfo,
373                                unsigned Flags) : pos(0) {
374   assert(Filename != 0 && "Filename is null");
375   // Verify that we don't have both "append" and "excl".
376   assert((!(Flags & F_Excl) || !(Flags & F_Append)) &&
377          "Cannot specify both 'excl' and 'append' file creation flags!");
378
379   ErrorInfo.clear();
380
381   // Handle "-" as stdout. Note that when we do this, we consider ourself
382   // the owner of stdout. This means that we can do things like close the
383   // file descriptor when we're done and set the "binary" flag globally.
384   if (Filename[0] == '-' && Filename[1] == 0) {
385     FD = STDOUT_FILENO;
386     // If user requested binary then put stdout into binary mode if
387     // possible.
388     if (Flags & F_Binary)
389       sys::Program::ChangeStdoutToBinary();
390     // Close stdout when we're done, to detect any output errors.
391     ShouldClose = true;
392     return;
393   }
394
395   int OpenFlags = O_WRONLY|O_CREAT;
396 #ifdef O_BINARY
397   if (Flags & F_Binary)
398     OpenFlags |= O_BINARY;
399 #endif
400
401   if (Flags & F_Append)
402     OpenFlags |= O_APPEND;
403   else
404     OpenFlags |= O_TRUNC;
405   if (Flags & F_Excl)
406     OpenFlags |= O_EXCL;
407
408   while ((FD = open(Filename, OpenFlags, 0664)) < 0) {
409     if (errno != EINTR) {
410       ErrorInfo = "Error opening output file '" + std::string(Filename) + "'";
411       ShouldClose = false;
412       return;
413     }
414   }
415
416   // Ok, we successfully opened the file, so it'll need to be closed.
417   ShouldClose = true;
418 }
419
420 raw_fd_ostream::~raw_fd_ostream() {
421   if (FD < 0) return;
422   flush();
423   if (ShouldClose)
424     while (::close(FD) != 0)
425       if (errno != EINTR) {
426         error_detected();
427         break;
428       }
429 }
430
431
432 void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) {
433   assert(FD >= 0 && "File already closed.");
434   pos += Size;
435
436   do {
437     ssize_t ret = ::write(FD, Ptr, Size);
438
439     if (ret < 0) {
440       // If it's a recoverable error, swallow it and retry the write.
441       //
442       // Ideally we wouldn't ever see EAGAIN or EWOULDBLOCK here, since
443       // raw_ostream isn't designed to do non-blocking I/O. However, some
444       // programs, such as old versions of bjam, have mistakenly used
445       // O_NONBLOCK. For compatibility, emulate blocking semantics by
446       // spinning until the write succeeds. If you don't want spinning,
447       // don't use O_NONBLOCK file descriptors with raw_ostream.
448       if (errno == EINTR || errno == EAGAIN
449 #ifdef EWOULDBLOCK
450           || errno == EWOULDBLOCK
451 #endif
452           )
453         continue;
454
455       // Otherwise it's a non-recoverable error. Note it and quit.
456       error_detected();
457       break;
458     }
459
460     // The write may have written some or all of the data. Update the
461     // size and buffer pointer to reflect the remainder that needs
462     // to be written. If there are no bytes left, we're done.
463     Ptr += ret;
464     Size -= ret;
465   } while (Size > 0);
466 }
467
468 void raw_fd_ostream::close() {
469   assert(ShouldClose);
470   ShouldClose = false;
471   flush();
472   while (::close(FD) != 0)
473     if (errno != EINTR) {
474       error_detected();
475       break;
476     }
477   FD = -1;
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 }
673
674 //===----------------------------------------------------------------------===//
675 //  tool_output_file
676 //===----------------------------------------------------------------------===//
677
678 /// SetupRemoveOnSignal - This is a helper for tool_output_file's constructor
679 /// to allow the signal handlers to be installed before constructing the
680 /// base class raw_fd_ostream.
681 static const char *SetupRemoveOnSignal(const char *Filename) {
682   // Arrange for the file to be deleted if the process is killed.
683   if (strcmp(Filename, "-") != 0)
684     sys::RemoveFileOnSignal(sys::Path(Filename));
685   return Filename;
686 }
687
688 tool_output_file::tool_output_file(const char *filename, std::string &ErrorInfo, 
689                                    unsigned Flags)
690   : raw_fd_ostream(SetupRemoveOnSignal(filename), ErrorInfo, Flags),
691     Filename(filename),
692     Keep(!ErrorInfo.empty() /* If open fails, no cleanup is needed. */) {
693 }
694
695 tool_output_file::~tool_output_file() {
696   // Delete the file if the client hasn't told us not to.
697   if (!Keep && Filename != "-")
698     sys::Path(Filename).eraseFromDisk();
699 }