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/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"
26 #include <sys/types.h>
28 #if defined(HAVE_UNISTD_H)
31 #if defined(HAVE_FCNTL_H)
39 # define STDIN_FILENO 0
42 # define STDOUT_FILENO 1
45 # define STDERR_FILENO 2
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!");
57 if (BufferMode == InternalBuffer)
58 delete [] OutBufStart;
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.
65 report_fatal_error("IO failure on output stream.");
68 // An out of line virtual method to provide a home for the class vtable.
69 void raw_ostream::handle() {}
71 size_t raw_ostream::preferred_buffer_size() const {
72 // BUFSIZ is intended to be a reasonable default.
76 void raw_ostream::SetBuffered() {
77 // Ask the subclass to determine an appropriate buffer size.
78 if (size_t Size = preferred_buffer_size())
81 // It may return 0, meaning this stream should be unbuffered.
85 void raw_ostream::SetBufferAndMode(char *BufferStart, size_t Size,
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!");
94 if (BufferMode == InternalBuffer)
95 delete [] OutBufStart;
96 OutBufStart = BufferStart;
97 OutBufEnd = OutBufStart+Size;
98 OutBufCur = OutBufStart;
101 assert(OutBufStart <= OutBufEnd && "Invalid size!");
104 raw_ostream &raw_ostream::operator<<(unsigned long N) {
105 // Zero is a special case.
109 char NumberBuffer[20];
110 char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
111 char *CurPtr = EndPtr;
114 *--CurPtr = '0' + char(N % 10);
117 return write(CurPtr, EndPtr-CurPtr);
120 raw_ostream &raw_ostream::operator<<(long N) {
126 return this->operator<<(static_cast<unsigned long>(N));
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));
134 char NumberBuffer[20];
135 char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
136 char *CurPtr = EndPtr;
139 *--CurPtr = '0' + char(N % 10);
142 return write(CurPtr, EndPtr-CurPtr);
145 raw_ostream &raw_ostream::operator<<(long long N) {
151 return this->operator<<(static_cast<unsigned long long>(N));
154 raw_ostream &raw_ostream::write_hex(unsigned long long N) {
155 // Zero is a special case.
159 char NumberBuffer[20];
160 char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
161 char *CurPtr = EndPtr;
164 uintptr_t x = N % 16;
165 *--CurPtr = (x < 10 ? '0' + x : 'a' + x - 10);
169 return write(CurPtr, EndPtr-CurPtr);
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];
178 *this << '\\' << '\\';
181 *this << '\\' << 't';
184 *this << '\\' << 'n';
187 *this << '\\' << '"';
190 if (std::isprint(c)) {
195 // Always expand to a 3-character octal escape.
197 *this << char('0' + ((c >> 6) & 7));
198 *this << char('0' + ((c >> 3) & 7));
199 *this << char('0' + ((c >> 0) & 7));
206 raw_ostream &raw_ostream::operator<<(const void *P) {
209 return write_hex((uintptr_t) P);
212 raw_ostream &raw_ostream::operator<<(double N) {
213 return this->operator<<(format("%e", N));
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);
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);
233 // Set up a buffer and start over.
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);
253 // Set up a buffer and start over.
255 return write(Ptr, Size);
258 // Write out the data in buffer-sized blocks until the remainder
259 // fits within the buffer.
261 size_t NumBytes = OutBufEnd - OutBufCur;
262 copy_to_buffer(Ptr, NumBytes);
266 } while (OutBufCur+Size > OutBufEnd);
269 copy_to_buffer(Ptr, Size);
274 void raw_ostream::copy_to_buffer(const char *Ptr, size_t Size) {
275 assert(Size <= size_t(OutBufEnd - OutBufCur) && "Buffer overrun!");
277 // Handle short strings specially, memcpy isn't very good at very short
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
286 memcpy(OutBufCur, Ptr, Size);
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);
302 // Common case is that we have plenty of space.
303 if (BytesUsed <= BufferBytesLeft) {
304 OutBufCur += BytesUsed;
308 // Otherwise, we overflowed and the return value tells us the size to try
310 NextBufferSize = BytesUsed;
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;
319 V.resize(NextBufferSize);
321 // Try formatting into the SmallVector.
322 size_t BytesUsed = Fmt.print(V.data(), NextBufferSize);
324 // If BytesUsed fit into the vector, we win.
325 if (BytesUsed <= NextBufferSize)
326 return write(V.data(), BytesUsed);
328 // Otherwise, try again with a new size.
329 assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?");
330 NextBufferSize = BytesUsed;
334 /// indent - Insert 'NumSpaces' spaces.
335 raw_ostream &raw_ostream::indent(unsigned NumSpaces) {
336 static const char Spaces[] = " "
340 // Usually the indentation is small, handle it with a fastpath.
341 if (NumSpaces < array_lengthof(Spaces))
342 return write(Spaces, NumSpaces);
345 unsigned NumToWrite = std::min(NumSpaces,
346 (unsigned)array_lengthof(Spaces)-1);
347 write(Spaces, NumToWrite);
348 NumSpaces -= NumToWrite;
354 //===----------------------------------------------------------------------===//
356 //===----------------------------------------------------------------------===//
358 // Out of line virtual method.
359 void format_object_base::home() {
362 //===----------------------------------------------------------------------===//
364 //===----------------------------------------------------------------------===//
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!");
379 // Handle "-" as stdout.
380 if (Filename[0] == '-' && Filename[1] == 0) {
382 // If user requested binary then put stdout into binary mode if
384 if (Flags & F_Binary)
385 sys::Program::ChangeStdoutToBinary();
390 int OpenFlags = O_WRONLY|O_CREAT;
392 if (Flags & F_Binary)
393 OpenFlags |= O_BINARY;
396 if (Flags & F_Append)
397 OpenFlags |= O_APPEND;
399 OpenFlags |= O_TRUNC;
403 while ((FD = open(Filename, OpenFlags, 0664)) < 0) {
404 if (errno != EINTR) {
405 ErrorInfo = "Error opening output file '" + std::string(Filename) + "'";
411 // Ok, we successfully opened the file, so it'll need to be closed.
415 raw_fd_ostream::~raw_fd_ostream() {
419 while (::close(FD) != 0)
420 if (errno != EINTR) {
427 void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) {
428 assert(FD >= 0 && "File already closed.");
432 ssize_t ret = ::write(FD, Ptr, Size);
435 // If it's a recoverable error, swallow it and retry the write.
437 // Ideally we wouldn't ever see EAGAIN or EWOULDBLOCK here, since
438 // raw_ostream isn't designed to do non-blocking I/O. However, some
439 // programs, such as old versions of bjam, have mistakenly used
440 // O_NONBLOCK. For compatibility, emulate blocking semantics by
441 // spinning until the write succeeds. If you don't want spinning,
442 // don't use O_NONBLOCK file descriptors with raw_ostream.
443 if (errno == EINTR || errno == EAGAIN
445 || errno == EWOULDBLOCK
450 // Otherwise it's a non-recoverable error. Note it and quit.
455 // The write may have written some or all of the data. Update the
456 // size and buffer pointer to reflect the remainder that needs
457 // to be written. If there are no bytes left, we're done.
463 void raw_fd_ostream::close() {
467 while (::close(FD) != 0)
468 if (errno != EINTR) {
475 uint64_t raw_fd_ostream::seek(uint64_t off) {
477 pos = ::lseek(FD, off, SEEK_SET);
483 size_t raw_fd_ostream::preferred_buffer_size() const {
484 #if !defined(_MSC_VER) && !defined(__MINGW32__) && !defined(__minix)
485 // Windows and Minix have no st_blksize.
486 assert(FD >= 0 && "File not yet open!");
488 if (fstat(FD, &statbuf) != 0)
491 // If this is a terminal, don't use buffering. Line buffering
492 // would be a more traditional thing to do, but it's not worth
494 if (S_ISCHR(statbuf.st_mode) && isatty(FD))
496 // Return the preferred block size.
497 return statbuf.st_blksize;
499 return raw_ostream::preferred_buffer_size();
503 raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold,
505 if (sys::Process::ColorNeedsFlush())
507 const char *colorcode =
508 (colors == SAVEDCOLOR) ? sys::Process::OutputBold(bg)
509 : sys::Process::OutputColor(colors, bold, bg);
511 size_t len = strlen(colorcode);
512 write(colorcode, len);
513 // don't account colors towards output characters
519 raw_ostream &raw_fd_ostream::resetColor() {
520 if (sys::Process::ColorNeedsFlush())
522 const char *colorcode = sys::Process::ResetColor();
524 size_t len = strlen(colorcode);
525 write(colorcode, len);
526 // don't account colors towards output characters
532 bool raw_fd_ostream::is_displayed() const {
533 return sys::Process::FileDescriptorIsDisplayed(FD);
536 //===----------------------------------------------------------------------===//
537 // raw_stdout/err_ostream
538 //===----------------------------------------------------------------------===//
540 // Set buffer settings to model stdout and stderr behavior.
541 // Set standard error to be unbuffered by default.
542 raw_stdout_ostream::raw_stdout_ostream():raw_fd_ostream(STDOUT_FILENO, false) {}
543 raw_stderr_ostream::raw_stderr_ostream():raw_fd_ostream(STDERR_FILENO, false,
546 // An out of line virtual method to provide a home for the class vtable.
547 void raw_stdout_ostream::handle() {}
548 void raw_stderr_ostream::handle() {}
550 /// outs() - This returns a reference to a raw_ostream for standard output.
551 /// Use it like: outs() << "foo" << "bar";
552 raw_ostream &llvm::outs() {
553 static raw_stdout_ostream S;
557 /// errs() - This returns a reference to a raw_ostream for standard error.
558 /// Use it like: errs() << "foo" << "bar";
559 raw_ostream &llvm::errs() {
560 static raw_stderr_ostream S;
564 /// nulls() - This returns a reference to a raw_ostream which discards output.
565 raw_ostream &llvm::nulls() {
566 static raw_null_ostream S;
571 //===----------------------------------------------------------------------===//
572 // raw_string_ostream
573 //===----------------------------------------------------------------------===//
575 raw_string_ostream::~raw_string_ostream() {
579 void raw_string_ostream::write_impl(const char *Ptr, size_t Size) {
580 OS.append(Ptr, Size);
583 //===----------------------------------------------------------------------===//
584 // raw_svector_ostream
585 //===----------------------------------------------------------------------===//
587 // The raw_svector_ostream implementation uses the SmallVector itself as the
588 // buffer for the raw_ostream. We guarantee that the raw_ostream buffer is
589 // always pointing past the end of the vector, but within the vector
590 // capacity. This allows raw_ostream to write directly into the correct place,
591 // and we only need to set the vector size when the data is flushed.
593 raw_svector_ostream::raw_svector_ostream(SmallVectorImpl<char> &O) : OS(O) {
594 // Set up the initial external buffer. We make sure that the buffer has at
595 // least 128 bytes free; raw_ostream itself only requires 64, but we want to
596 // make sure that we don't grow the buffer unnecessarily on destruction (when
597 // the data is flushed). See the FIXME below.
598 OS.reserve(OS.size() + 128);
599 SetBuffer(OS.end(), OS.capacity() - OS.size());
602 raw_svector_ostream::~raw_svector_ostream() {
603 // FIXME: Prevent resizing during this flush().
607 /// resync - This is called when the SmallVector we're appending to is changed
608 /// outside of the raw_svector_ostream's control. It is only safe to do this
609 /// if the raw_svector_ostream has previously been flushed.
610 void raw_svector_ostream::resync() {
611 assert(GetNumBytesInBuffer() == 0 && "Didn't flush before mutating vector");
613 if (OS.capacity() - OS.size() < 64)
614 OS.reserve(OS.capacity() * 2);
615 SetBuffer(OS.end(), OS.capacity() - OS.size());
618 void raw_svector_ostream::write_impl(const char *Ptr, size_t Size) {
619 // If we're writing bytes from the end of the buffer into the smallvector, we
620 // don't need to copy the bytes, just commit the bytes because they are
621 // already in the right place.
622 if (Ptr == OS.end()) {
623 assert(OS.size() + Size <= OS.capacity() && "Invalid write_impl() call!");
624 OS.set_size(OS.size() + Size);
626 assert(GetNumBytesInBuffer() == 0 &&
627 "Should be writing from buffer if some bytes in it");
628 // Otherwise, do copy the bytes.
629 OS.append(Ptr, Ptr+Size);
632 // Grow the vector if necessary.
633 if (OS.capacity() - OS.size() < 64)
634 OS.reserve(OS.capacity() * 2);
636 // Update the buffer position.
637 SetBuffer(OS.end(), OS.capacity() - OS.size());
640 uint64_t raw_svector_ostream::current_pos() const {
644 StringRef raw_svector_ostream::str() {
646 return StringRef(OS.begin(), OS.size());
649 //===----------------------------------------------------------------------===//
651 //===----------------------------------------------------------------------===//
653 raw_null_ostream::~raw_null_ostream() {
655 // ~raw_ostream asserts that the buffer is empty. This isn't necessary
656 // with raw_null_ostream, but it's better to have raw_null_ostream follow
657 // the rules than to change the rules just for raw_null_ostream.
662 void raw_null_ostream::write_impl(const char *Ptr, size_t Size) {
665 uint64_t raw_null_ostream::current_pos() const {