1 //===--- raw_ostream.cpp - Implement the raw_ostream classes --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements support for bulk buffered stream output.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Support/raw_ostream.h"
15 #include "llvm/Support/Format.h"
16 #include "llvm/Support/Program.h"
17 #include "llvm/Support/Process.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/Config/config.h"
21 #include "llvm/Support/Compiler.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/system_error.h"
24 #include "llvm/ADT/STLExtras.h"
28 #include <sys/types.h>
30 #if defined(HAVE_UNISTD_H)
33 #if defined(HAVE_FCNTL_H)
36 #if defined(HAVE_SYS_UIO_H) && defined(HAVE_WRITEV)
40 #if defined(__CYGWIN__)
48 # define STDIN_FILENO 0
51 # define STDOUT_FILENO 1
54 # define STDERR_FILENO 2
60 raw_ostream::~raw_ostream() {
61 // raw_ostream's subclasses should take care to flush the buffer
62 // in their destructors.
63 assert(OutBufCur == OutBufStart &&
64 "raw_ostream destructor called with non-empty buffer!");
66 if (BufferMode == InternalBuffer)
67 delete [] OutBufStart;
70 // An out of line virtual method to provide a home for the class vtable.
71 void raw_ostream::handle() {}
73 size_t raw_ostream::preferred_buffer_size() const {
74 // BUFSIZ is intended to be a reasonable default.
78 void raw_ostream::SetBuffered() {
79 // Ask the subclass to determine an appropriate buffer size.
80 if (size_t Size = preferred_buffer_size())
83 // It may return 0, meaning this stream should be unbuffered.
87 void raw_ostream::SetBufferAndMode(char *BufferStart, size_t Size,
89 assert(((Mode == Unbuffered && BufferStart == 0 && Size == 0) ||
90 (Mode != Unbuffered && BufferStart && Size)) &&
91 "stream must be unbuffered or have at least one byte");
92 // Make sure the current buffer is free of content (we can't flush here; the
93 // child buffer management logic will be in write_impl).
94 assert(GetNumBytesInBuffer() == 0 && "Current buffer is non-empty!");
96 if (BufferMode == InternalBuffer)
97 delete [] OutBufStart;
98 OutBufStart = BufferStart;
99 OutBufEnd = OutBufStart+Size;
100 OutBufCur = OutBufStart;
103 assert(OutBufStart <= OutBufEnd && "Invalid size!");
106 raw_ostream &raw_ostream::operator<<(unsigned long N) {
107 // Zero is a special case.
111 char NumberBuffer[20];
112 char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
113 char *CurPtr = EndPtr;
116 *--CurPtr = '0' + char(N % 10);
119 return write(CurPtr, EndPtr-CurPtr);
122 raw_ostream &raw_ostream::operator<<(long N) {
125 // Avoid undefined behavior on LONG_MIN with a cast.
126 N = -(unsigned long)N;
129 return this->operator<<(static_cast<unsigned long>(N));
132 raw_ostream &raw_ostream::operator<<(unsigned long long N) {
133 // Output using 32-bit div/mod when possible.
134 if (N == static_cast<unsigned long>(N))
135 return this->operator<<(static_cast<unsigned long>(N));
137 char NumberBuffer[20];
138 char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
139 char *CurPtr = EndPtr;
142 *--CurPtr = '0' + char(N % 10);
145 return write(CurPtr, EndPtr-CurPtr);
148 raw_ostream &raw_ostream::operator<<(long long N) {
151 // Avoid undefined behavior on INT64_MIN with a cast.
152 N = -(unsigned long long)N;
155 return this->operator<<(static_cast<unsigned long long>(N));
158 raw_ostream &raw_ostream::write_hex(unsigned long long N) {
159 // Zero is a special case.
163 char NumberBuffer[20];
164 char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
165 char *CurPtr = EndPtr;
168 uintptr_t x = N % 16;
169 *--CurPtr = (x < 10 ? '0' + x : 'a' + x - 10);
173 return write(CurPtr, EndPtr-CurPtr);
176 raw_ostream &raw_ostream::write_escaped(StringRef Str,
177 bool UseHexEscapes) {
178 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
179 unsigned char c = Str[i];
183 *this << '\\' << '\\';
186 *this << '\\' << 't';
189 *this << '\\' << 'n';
192 *this << '\\' << '"';
195 if (std::isprint(c)) {
200 // Write out the escaped representation.
202 *this << '\\' << 'x';
203 *this << hexdigit((c >> 4 & 0xF));
204 *this << hexdigit((c >> 0) & 0xF);
206 // Always use a full 3-character octal escape.
208 *this << char('0' + ((c >> 6) & 7));
209 *this << char('0' + ((c >> 3) & 7));
210 *this << char('0' + ((c >> 0) & 7));
218 raw_ostream &raw_ostream::operator<<(const void *P) {
221 return write_hex((uintptr_t) P);
224 raw_ostream &raw_ostream::operator<<(double N) {
226 // On MSVCRT and compatible, output of %e is incompatible to Posix
227 // by default. Number of exponent digits should be at least 2. "%+03d"
228 // FIXME: Implement our formatter to here or Support/Format.h!
229 int fpcl = _fpclass(N);
232 if (fpcl == _FPCLASS_NZ)
233 return *this << "-0.000000e+00";
237 len = snprintf(buf, sizeof(buf), "%e", N);
238 if (len <= sizeof(buf) - 2) {
239 if (len >= 5 && buf[len - 5] == 'e' && buf[len - 3] == '0') {
240 int cs = buf[len - 4];
241 if (cs == '+' || cs == '-') {
242 int c1 = buf[len - 2];
243 int c0 = buf[len - 1];
244 if (isdigit(c1) && isdigit(c0)) {
245 // Trim leading '0': "...e+012" -> "...e+12\0"
252 return this->operator<<(buf);
255 return this->operator<<(format("%e", N));
260 void raw_ostream::flush_nonempty() {
261 assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty.");
262 size_t Length = OutBufCur - OutBufStart;
263 OutBufCur = OutBufStart;
264 write_impl(OutBufStart, Length);
267 raw_ostream &raw_ostream::write(unsigned char C) {
268 // Group exceptional cases into a single branch.
269 if (BUILTIN_EXPECT(OutBufCur >= OutBufEnd, false)) {
270 if (BUILTIN_EXPECT(!OutBufStart, false)) {
271 if (BufferMode == Unbuffered) {
272 write_impl(reinterpret_cast<char*>(&C), 1);
275 // Set up a buffer and start over.
287 raw_ostream &raw_ostream::write(const char *Ptr, size_t Size) {
288 // Group exceptional cases into a single branch.
289 if (BUILTIN_EXPECT(size_t(OutBufEnd - OutBufCur) < Size, false)) {
290 if (BUILTIN_EXPECT(!OutBufStart, false)) {
291 if (BufferMode == Unbuffered) {
292 write_impl(Ptr, Size);
295 // Set up a buffer and start over.
297 return write(Ptr, Size);
300 size_t NumBytes = OutBufEnd - OutBufCur;
302 // If the buffer is empty at this point we have a string that is larger
303 // than the buffer. Directly write the chunk that is a multiple of the
304 // preferred buffer size and put the remainder in the buffer.
305 if (BUILTIN_EXPECT(OutBufCur == OutBufStart, false)) {
306 size_t BytesToWrite = Size - (Size % NumBytes);
307 write_impl(Ptr, BytesToWrite);
308 copy_to_buffer(Ptr + BytesToWrite, Size - BytesToWrite);
312 // We don't have enough space in the buffer to fit the string in. Insert as
313 // much as possible, flush and start over with the remainder.
314 copy_to_buffer(Ptr, NumBytes);
316 return write(Ptr + NumBytes, Size - NumBytes);
319 copy_to_buffer(Ptr, Size);
324 void raw_ostream::copy_to_buffer(const char *Ptr, size_t Size) {
325 assert(Size <= size_t(OutBufEnd - OutBufCur) && "Buffer overrun!");
327 // Handle short strings specially, memcpy isn't very good at very short
330 case 4: OutBufCur[3] = Ptr[3]; // FALL THROUGH
331 case 3: OutBufCur[2] = Ptr[2]; // FALL THROUGH
332 case 2: OutBufCur[1] = Ptr[1]; // FALL THROUGH
333 case 1: OutBufCur[0] = Ptr[0]; // FALL THROUGH
336 memcpy(OutBufCur, Ptr, Size);
344 raw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) {
345 // If we have more than a few bytes left in our output buffer, try
346 // formatting directly onto its end.
347 size_t NextBufferSize = 127;
348 size_t BufferBytesLeft = OutBufEnd - OutBufCur;
349 if (BufferBytesLeft > 3) {
350 size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft);
352 // Common case is that we have plenty of space.
353 if (BytesUsed <= BufferBytesLeft) {
354 OutBufCur += BytesUsed;
358 // Otherwise, we overflowed and the return value tells us the size to try
360 NextBufferSize = BytesUsed;
363 // If we got here, we didn't have enough space in the output buffer for the
364 // string. Try printing into a SmallVector that is resized to have enough
365 // space. Iterate until we win.
366 SmallVector<char, 128> V;
369 V.resize(NextBufferSize);
371 // Try formatting into the SmallVector.
372 size_t BytesUsed = Fmt.print(V.data(), NextBufferSize);
374 // If BytesUsed fit into the vector, we win.
375 if (BytesUsed <= NextBufferSize)
376 return write(V.data(), BytesUsed);
378 // Otherwise, try again with a new size.
379 assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?");
380 NextBufferSize = BytesUsed;
384 /// indent - Insert 'NumSpaces' spaces.
385 raw_ostream &raw_ostream::indent(unsigned NumSpaces) {
386 static const char Spaces[] = " "
390 // Usually the indentation is small, handle it with a fastpath.
391 if (NumSpaces < array_lengthof(Spaces))
392 return write(Spaces, NumSpaces);
395 unsigned NumToWrite = std::min(NumSpaces,
396 (unsigned)array_lengthof(Spaces)-1);
397 write(Spaces, NumToWrite);
398 NumSpaces -= NumToWrite;
404 //===----------------------------------------------------------------------===//
406 //===----------------------------------------------------------------------===//
408 // Out of line virtual method.
409 void format_object_base::home() {
412 //===----------------------------------------------------------------------===//
414 //===----------------------------------------------------------------------===//
416 /// raw_fd_ostream - Open the specified file for writing. If an error
417 /// occurs, information about the error is put into ErrorInfo, and the
418 /// stream should be immediately destroyed; the string will be empty
419 /// if no error occurred.
420 raw_fd_ostream::raw_fd_ostream(const char *Filename, std::string &ErrorInfo,
422 : Error(false), UseAtomicWrites(false), pos(0)
424 assert(Filename != 0 && "Filename is null");
425 // Verify that we don't have both "append" and "excl".
426 assert((!(Flags & F_Excl) || !(Flags & F_Append)) &&
427 "Cannot specify both 'excl' and 'append' file creation flags!");
431 // Handle "-" as stdout. Note that when we do this, we consider ourself
432 // the owner of stdout. This means that we can do things like close the
433 // file descriptor when we're done and set the "binary" flag globally.
434 if (Filename[0] == '-' && Filename[1] == 0) {
436 // If user requested binary then put stdout into binary mode if
438 if (Flags & F_Binary)
439 sys::Program::ChangeStdoutToBinary();
440 // Close stdout when we're done, to detect any output errors.
445 int OpenFlags = O_WRONLY|O_CREAT;
447 if (Flags & F_Binary)
448 OpenFlags |= O_BINARY;
451 if (Flags & F_Append)
452 OpenFlags |= O_APPEND;
454 OpenFlags |= O_TRUNC;
458 while ((FD = open(Filename, OpenFlags, 0664)) < 0) {
459 if (errno != EINTR) {
460 ErrorInfo = "Error opening output file '" + std::string(Filename) + "'";
466 // Ok, we successfully opened the file, so it'll need to be closed.
470 /// raw_fd_ostream ctor - FD is the file descriptor that this writes to. If
471 /// ShouldClose is true, this closes the file when the stream is destroyed.
472 raw_fd_ostream::raw_fd_ostream(int fd, bool shouldClose, bool unbuffered)
473 : raw_ostream(unbuffered), FD(fd),
474 ShouldClose(shouldClose), Error(false), UseAtomicWrites(false) {
476 // Setting STDOUT and STDERR to binary mode is necessary in Win32
477 // to avoid undesirable linefeed conversion.
478 if (fd == STDOUT_FILENO || fd == STDERR_FILENO)
479 setmode(fd, O_BINARY);
482 // Get the starting position.
483 off_t loc = ::lseek(FD, 0, SEEK_CUR);
484 if (loc == (off_t)-1)
487 pos = static_cast<uint64_t>(loc);
490 raw_fd_ostream::~raw_fd_ostream() {
494 while (::close(FD) != 0)
495 if (errno != EINTR) {
502 // On mingw, global dtors should not call exit().
503 // report_fatal_error() invokes exit(). We know report_fatal_error()
504 // might not write messages to stderr when any errors were detected
509 // If there are any pending errors, report them now. Clients wishing
510 // to avoid report_fatal_error calls should check for errors with
511 // has_error() and clear the error flag with clear_error() before
512 // destructing raw_ostream objects which may have errors.
514 report_fatal_error("IO failure on output stream.");
518 void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) {
519 assert(FD >= 0 && "File already closed.");
525 // Check whether we should attempt to use atomic writes.
526 if (BUILTIN_EXPECT(!UseAtomicWrites, true)) {
527 ret = ::write(FD, Ptr, Size);
529 // Use ::writev() where available.
530 #if defined(HAVE_WRITEV)
531 struct iovec IOV = { (void*) Ptr, Size };
532 ret = ::writev(FD, &IOV, 1);
534 ret = ::write(FD, Ptr, Size);
539 // If it's a recoverable error, swallow it and retry the write.
541 // Ideally we wouldn't ever see EAGAIN or EWOULDBLOCK here, since
542 // raw_ostream isn't designed to do non-blocking I/O. However, some
543 // programs, such as old versions of bjam, have mistakenly used
544 // O_NONBLOCK. For compatibility, emulate blocking semantics by
545 // spinning until the write succeeds. If you don't want spinning,
546 // don't use O_NONBLOCK file descriptors with raw_ostream.
547 if (errno == EINTR || errno == EAGAIN
549 || errno == EWOULDBLOCK
554 // Otherwise it's a non-recoverable error. Note it and quit.
559 // The write may have written some or all of the data. Update the
560 // size and buffer pointer to reflect the remainder that needs
561 // to be written. If there are no bytes left, we're done.
567 void raw_fd_ostream::close() {
571 while (::close(FD) != 0)
572 if (errno != EINTR) {
579 uint64_t raw_fd_ostream::seek(uint64_t off) {
581 pos = ::lseek(FD, off, SEEK_SET);
587 size_t raw_fd_ostream::preferred_buffer_size() const {
588 #if !defined(_MSC_VER) && !defined(__MINGW32__) && !defined(__minix)
589 // Windows and Minix have no st_blksize.
590 assert(FD >= 0 && "File not yet open!");
592 if (fstat(FD, &statbuf) != 0)
595 // If this is a terminal, don't use buffering. Line buffering
596 // would be a more traditional thing to do, but it's not worth
598 if (S_ISCHR(statbuf.st_mode) && isatty(FD))
600 // Return the preferred block size.
601 return statbuf.st_blksize;
603 return raw_ostream::preferred_buffer_size();
607 raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold,
609 if (sys::Process::ColorNeedsFlush())
611 const char *colorcode =
612 (colors == SAVEDCOLOR) ? sys::Process::OutputBold(bg)
613 : sys::Process::OutputColor(colors, bold, bg);
615 size_t len = strlen(colorcode);
616 write(colorcode, len);
617 // don't account colors towards output characters
623 raw_ostream &raw_fd_ostream::resetColor() {
624 if (sys::Process::ColorNeedsFlush())
626 const char *colorcode = sys::Process::ResetColor();
628 size_t len = strlen(colorcode);
629 write(colorcode, len);
630 // don't account colors towards output characters
636 bool raw_fd_ostream::is_displayed() const {
637 return sys::Process::FileDescriptorIsDisplayed(FD);
640 //===----------------------------------------------------------------------===//
641 // outs(), errs(), nulls()
642 //===----------------------------------------------------------------------===//
644 /// outs() - This returns a reference to a raw_ostream for standard output.
645 /// Use it like: outs() << "foo" << "bar";
646 raw_ostream &llvm::outs() {
647 // Set buffer settings to model stdout behavior.
648 // Delete the file descriptor when the program exists, forcing error
649 // detection. If you don't want this behavior, don't use outs().
650 static raw_fd_ostream S(STDOUT_FILENO, true);
654 /// errs() - This returns a reference to a raw_ostream for standard error.
655 /// Use it like: errs() << "foo" << "bar";
656 raw_ostream &llvm::errs() {
657 // Set standard error to be unbuffered by default.
658 static raw_fd_ostream S(STDERR_FILENO, false, true);
662 /// nulls() - This returns a reference to a raw_ostream which discards output.
663 raw_ostream &llvm::nulls() {
664 static raw_null_ostream S;
669 //===----------------------------------------------------------------------===//
670 // raw_string_ostream
671 //===----------------------------------------------------------------------===//
673 raw_string_ostream::~raw_string_ostream() {
677 void raw_string_ostream::write_impl(const char *Ptr, size_t Size) {
678 OS.append(Ptr, Size);
681 //===----------------------------------------------------------------------===//
682 // raw_svector_ostream
683 //===----------------------------------------------------------------------===//
685 // The raw_svector_ostream implementation uses the SmallVector itself as the
686 // buffer for the raw_ostream. We guarantee that the raw_ostream buffer is
687 // always pointing past the end of the vector, but within the vector
688 // capacity. This allows raw_ostream to write directly into the correct place,
689 // and we only need to set the vector size when the data is flushed.
691 raw_svector_ostream::raw_svector_ostream(SmallVectorImpl<char> &O) : OS(O) {
692 // Set up the initial external buffer. We make sure that the buffer has at
693 // least 128 bytes free; raw_ostream itself only requires 64, but we want to
694 // make sure that we don't grow the buffer unnecessarily on destruction (when
695 // the data is flushed). See the FIXME below.
696 OS.reserve(OS.size() + 128);
697 SetBuffer(OS.end(), OS.capacity() - OS.size());
700 raw_svector_ostream::~raw_svector_ostream() {
701 // FIXME: Prevent resizing during this flush().
705 /// resync - This is called when the SmallVector we're appending to is changed
706 /// outside of the raw_svector_ostream's control. It is only safe to do this
707 /// if the raw_svector_ostream has previously been flushed.
708 void raw_svector_ostream::resync() {
709 assert(GetNumBytesInBuffer() == 0 && "Didn't flush before mutating vector");
711 if (OS.capacity() - OS.size() < 64)
712 OS.reserve(OS.capacity() * 2);
713 SetBuffer(OS.end(), OS.capacity() - OS.size());
716 void raw_svector_ostream::write_impl(const char *Ptr, size_t Size) {
717 // If we're writing bytes from the end of the buffer into the smallvector, we
718 // don't need to copy the bytes, just commit the bytes because they are
719 // already in the right place.
720 if (Ptr == OS.end()) {
721 assert(OS.size() + Size <= OS.capacity() && "Invalid write_impl() call!");
722 OS.set_size(OS.size() + Size);
724 assert(GetNumBytesInBuffer() == 0 &&
725 "Should be writing from buffer if some bytes in it");
726 // Otherwise, do copy the bytes.
727 OS.append(Ptr, Ptr+Size);
730 // Grow the vector if necessary.
731 if (OS.capacity() - OS.size() < 64)
732 OS.reserve(OS.capacity() * 2);
734 // Update the buffer position.
735 SetBuffer(OS.end(), OS.capacity() - OS.size());
738 uint64_t raw_svector_ostream::current_pos() const {
742 StringRef raw_svector_ostream::str() {
744 return StringRef(OS.begin(), OS.size());
747 //===----------------------------------------------------------------------===//
749 //===----------------------------------------------------------------------===//
751 raw_null_ostream::~raw_null_ostream() {
753 // ~raw_ostream asserts that the buffer is empty. This isn't necessary
754 // with raw_null_ostream, but it's better to have raw_null_ostream follow
755 // the rules than to change the rules just for raw_null_ostream.
760 void raw_null_ostream::write_impl(const char *Ptr, size_t Size) {
763 uint64_t raw_null_ostream::current_pos() const {