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"
24 #include <sys/types.h>
26 #if defined(HAVE_UNISTD_H)
29 #if defined(HAVE_FCNTL_H)
37 # define STDIN_FILENO 0
40 # define STDOUT_FILENO 1
43 # define STDERR_FILENO 2
49 raw_ostream::~raw_ostream() {
50 // raw_ostream's subclasses should take care to flush the buffer
51 // in their destructors.
52 assert(OutBufCur == OutBufStart &&
53 "raw_ostream destructor called with non-empty buffer!");
55 if (BufferMode == InternalBuffer)
56 delete [] OutBufStart;
58 // If there are any pending errors, report them now. Clients wishing
59 // to avoid llvm_report_error calls should check for errors with
60 // has_error() and clear the error flag with clear_error() before
61 // destructing raw_ostream objects which may have errors.
63 llvm_report_error("IO failure on output stream.");
66 // An out of line virtual method to provide a home for the class vtable.
67 void raw_ostream::handle() {}
69 size_t raw_ostream::preferred_buffer_size() {
70 // BUFSIZ is intended to be a reasonable default.
74 void raw_ostream::SetBuffered() {
75 // Ask the subclass to determine an appropriate buffer size.
76 if (size_t Size = preferred_buffer_size())
79 // It may return 0, meaning this stream should be unbuffered.
83 void raw_ostream::SetBufferAndMode(char *BufferStart, size_t Size,
85 assert(((Mode == Unbuffered && BufferStart == 0 && Size == 0) ||
86 (Mode != Unbuffered && BufferStart && Size >= 64)) &&
87 "stream must be unbuffered, or have >= 64 bytes of buffer");
88 // Make sure the current buffer is free of content (we can't flush here; the
89 // child buffer management logic will be in write_impl).
90 assert(GetNumBytesInBuffer() == 0 && "Current buffer is non-empty!");
92 if (BufferMode == InternalBuffer)
93 delete [] OutBufStart;
94 OutBufStart = BufferStart;
95 OutBufEnd = OutBufStart+Size;
96 OutBufCur = OutBufStart;
100 raw_ostream &raw_ostream::operator<<(unsigned long N) {
101 // Zero is a special case.
105 char NumberBuffer[20];
106 char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
107 char *CurPtr = EndPtr;
110 *--CurPtr = '0' + char(N % 10);
113 return write(CurPtr, EndPtr-CurPtr);
116 raw_ostream &raw_ostream::operator<<(long N) {
122 return this->operator<<(static_cast<unsigned long>(N));
125 raw_ostream &raw_ostream::operator<<(unsigned long long N) {
126 // Handle simple case when value fits in long already.
127 if (N == static_cast<unsigned long>(N))
128 return this->operator<<(static_cast<unsigned long>(N));
130 // Otherwise divide into at two or three 10**9 chunks and write out using
131 // long div/mod, this is substantially faster on a 32-bit system.
132 unsigned long Top = 0, Mid = 0, Bot = N % 1000000000;
134 if (N > 1000000000) {
135 Mid = N % 1000000000;
136 Top = N / 1000000000;
141 this->operator<<(static_cast<unsigned long>(Top));
142 this->operator<<(static_cast<unsigned long>(Mid));
143 return this->operator<<(static_cast<unsigned long>(Bot));
146 raw_ostream &raw_ostream::operator<<(long long N) {
152 return this->operator<<(static_cast<unsigned long long>(N));
155 raw_ostream &raw_ostream::write_hex(unsigned long long N) {
156 // Zero is a special case.
160 char NumberBuffer[20];
161 char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
162 char *CurPtr = EndPtr;
165 uintptr_t x = N % 16;
166 *--CurPtr = (x < 10 ? '0' + x : 'a' + x - 10);
170 return write(CurPtr, EndPtr-CurPtr);
173 raw_ostream &raw_ostream::operator<<(const void *P) {
176 return write_hex((uintptr_t) P);
179 void raw_ostream::flush_nonempty() {
180 assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty.");
181 size_t Length = OutBufCur - OutBufStart;
182 OutBufCur = OutBufStart;
183 write_impl(OutBufStart, Length);
186 raw_ostream &raw_ostream::write(unsigned char C) {
187 // Group exceptional cases into a single branch.
188 if (OutBufCur >= OutBufEnd) {
189 if (BufferMode == Unbuffered) {
190 write_impl(reinterpret_cast<char*>(&C), 1);
198 // It's possible for the underlying stream to decline
199 // buffering, so check this condition again.
200 if (BufferMode == Unbuffered) {
201 write_impl(reinterpret_cast<char*>(&C), 1);
211 raw_ostream &raw_ostream::write(const char *Ptr, size_t Size) {
212 // Group exceptional cases into a single branch.
213 if (BUILTIN_EXPECT(OutBufCur+Size > OutBufEnd, false)) {
214 if (BUILTIN_EXPECT(!OutBufStart, false)) {
215 if (BufferMode == Unbuffered) {
216 write_impl(Ptr, Size);
219 // Set up a buffer and start over.
221 return write(Ptr, Size);
223 // Write out the data in buffer-sized blocks until the remainder
224 // fits within the buffer.
226 size_t NumBytes = OutBufEnd - OutBufCur;
227 copy_to_buffer(Ptr, NumBytes);
231 } while (OutBufCur+Size > OutBufEnd);
234 copy_to_buffer(Ptr, Size);
239 void raw_ostream::copy_to_buffer(const char *Ptr, size_t Size) {
240 assert(Size <= size_t(OutBufEnd - OutBufCur) && "Buffer overrun!");
242 // Handle short strings specially, memcpy isn't very good at very short
245 case 4: OutBufCur[3] = Ptr[3]; // FALL THROUGH
246 case 3: OutBufCur[2] = Ptr[2]; // FALL THROUGH
247 case 2: OutBufCur[1] = Ptr[1]; // FALL THROUGH
248 case 1: OutBufCur[0] = Ptr[0]; // FALL THROUGH
251 memcpy(OutBufCur, Ptr, Size);
259 raw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) {
260 // If we have more than a few bytes left in our output buffer, try
261 // formatting directly onto its end.
263 // FIXME: This test is a bit silly, since if we don't have enough
264 // space in the buffer we will have to flush the formatted output
265 // anyway. We should just flush upfront in such cases, and use the
266 // whole buffer as our scratch pad. Note, however, that this case is
267 // also necessary for correctness on unbuffered streams.
268 size_t NextBufferSize = 127;
269 if (OutBufEnd-OutBufCur > 3) {
270 size_t BufferBytesLeft = OutBufEnd-OutBufCur;
271 size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft);
273 // Common case is that we have plenty of space.
274 if (BytesUsed < BufferBytesLeft) {
275 OutBufCur += BytesUsed;
279 // Otherwise, we overflowed and the return value tells us the size to try
281 NextBufferSize = BytesUsed;
284 // If we got here, we didn't have enough space in the output buffer for the
285 // string. Try printing into a SmallVector that is resized to have enough
286 // space. Iterate until we win.
287 SmallVector<char, 128> V;
290 V.resize(NextBufferSize);
292 // Try formatting into the SmallVector.
293 size_t BytesUsed = Fmt.print(&V[0], NextBufferSize);
295 // If BytesUsed fit into the vector, we win.
296 if (BytesUsed <= NextBufferSize)
297 return write(&V[0], BytesUsed);
299 // Otherwise, try again with a new size.
300 assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?");
301 NextBufferSize = BytesUsed;
305 //===----------------------------------------------------------------------===//
307 //===----------------------------------------------------------------------===//
309 // Out of line virtual method.
310 void format_object_base::home() {
313 //===----------------------------------------------------------------------===//
315 //===----------------------------------------------------------------------===//
317 /// raw_fd_ostream - Open the specified file for writing. If an error
318 /// occurs, information about the error is put into ErrorInfo, and the
319 /// stream should be immediately destroyed; the string will be empty
320 /// if no error occurred.
321 raw_fd_ostream::raw_fd_ostream(const char *Filename, bool Binary, bool Force,
322 std::string &ErrorInfo) : pos(0) {
325 // Handle "-" as stdout.
326 if (Filename[0] == '-' && Filename[1] == 0) {
328 // If user requested binary then put stdout into binary mode if
331 sys::Program::ChangeStdoutToBinary();
336 int Flags = O_WRONLY|O_CREAT|O_TRUNC;
343 FD = open(Filename, Flags, 0664);
345 ErrorInfo = "Error opening output file '" + std::string(Filename) + "'";
352 raw_fd_ostream::~raw_fd_ostream() {
356 if (::close(FD) != 0)
361 void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) {
362 assert (FD >= 0 && "File already closed.");
364 if (::write(FD, Ptr, Size) != (ssize_t) Size)
368 void raw_fd_ostream::close() {
369 assert (ShouldClose);
372 if (::close(FD) != 0)
377 uint64_t raw_fd_ostream::seek(uint64_t off) {
379 pos = ::lseek(FD, off, SEEK_SET);
385 size_t raw_fd_ostream::preferred_buffer_size() {
386 #if !defined(_MSC_VER) && !defined(__MINGW32__) // Windows has no st_blksize.
387 assert(FD >= 0 && "File not yet open!");
389 if (fstat(FD, &statbuf) == 0) {
390 // If this is a terminal, don't use buffering. Line buffering
391 // would be a more traditional thing to do, but it's not worth
393 if (S_ISCHR(statbuf.st_mode) && isatty(FD))
395 // Return the preferred block size.
396 return statbuf.st_blksize;
400 return raw_ostream::preferred_buffer_size();
403 raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold,
405 if (sys::Process::ColorNeedsFlush())
407 const char *colorcode =
408 (colors == SAVEDCOLOR) ? sys::Process::OutputBold(bg)
409 : sys::Process::OutputColor(colors, bold, bg);
411 size_t len = strlen(colorcode);
412 write(colorcode, len);
413 // don't account colors towards output characters
419 raw_ostream &raw_fd_ostream::resetColor() {
420 if (sys::Process::ColorNeedsFlush())
422 const char *colorcode = sys::Process::ResetColor();
424 size_t len = strlen(colorcode);
425 write(colorcode, len);
426 // don't account colors towards output characters
432 //===----------------------------------------------------------------------===//
433 // raw_stdout/err_ostream
434 //===----------------------------------------------------------------------===//
436 // Set buffer settings to model stdout and stderr behavior.
437 // Set standard error to be unbuffered by default.
438 raw_stdout_ostream::raw_stdout_ostream():raw_fd_ostream(STDOUT_FILENO, false) {}
439 raw_stderr_ostream::raw_stderr_ostream():raw_fd_ostream(STDERR_FILENO, false,
442 // An out of line virtual method to provide a home for the class vtable.
443 void raw_stdout_ostream::handle() {}
444 void raw_stderr_ostream::handle() {}
446 /// outs() - This returns a reference to a raw_ostream for standard output.
447 /// Use it like: outs() << "foo" << "bar";
448 raw_ostream &llvm::outs() {
449 static raw_stdout_ostream S;
453 /// errs() - This returns a reference to a raw_ostream for standard error.
454 /// Use it like: errs() << "foo" << "bar";
455 raw_ostream &llvm::errs() {
456 static raw_stderr_ostream S;
460 /// nulls() - This returns a reference to a raw_ostream which discards output.
461 raw_ostream &llvm::nulls() {
462 static raw_null_ostream S;
466 //===----------------------------------------------------------------------===//
468 //===----------------------------------------------------------------------===//
470 raw_os_ostream::~raw_os_ostream() {
474 void raw_os_ostream::write_impl(const char *Ptr, size_t Size) {
478 uint64_t raw_os_ostream::current_pos() { return OS.tellp(); }
480 //===----------------------------------------------------------------------===//
481 // raw_string_ostream
482 //===----------------------------------------------------------------------===//
484 raw_string_ostream::~raw_string_ostream() {
488 void raw_string_ostream::write_impl(const char *Ptr, size_t Size) {
489 OS.append(Ptr, Size);
492 //===----------------------------------------------------------------------===//
493 // raw_svector_ostream
494 //===----------------------------------------------------------------------===//
496 raw_svector_ostream::raw_svector_ostream(SmallVectorImpl<char> &O) : OS(O) {
499 raw_svector_ostream::~raw_svector_ostream() {
503 void raw_svector_ostream::write_impl(const char *Ptr, size_t Size) {
504 OS.append(Ptr, Ptr + Size);
507 uint64_t raw_svector_ostream::current_pos() { return OS.size(); }
509 //===----------------------------------------------------------------------===//
511 //===----------------------------------------------------------------------===//
513 raw_null_ostream::~raw_null_ostream() {
515 // ~raw_ostream asserts that the buffer is empty. This isn't necessary
516 // with raw_null_ostream, but it's better to have raw_null_ostream follow
517 // the rules than to change the rules just for raw_null_ostream.
522 void raw_null_ostream::write_impl(const char *Ptr, size_t Size) {
525 uint64_t raw_null_ostream::current_pos() {