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 // Output using 32-bit div/mod when possible.
127 if (N == static_cast<unsigned long>(N))
128 return this->operator<<(static_cast<unsigned long>(N));
130 char NumberBuffer[20];
131 char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
132 char *CurPtr = EndPtr;
135 *--CurPtr = '0' + char(N % 10);
138 return write(CurPtr, EndPtr-CurPtr);
141 raw_ostream &raw_ostream::operator<<(long long N) {
147 return this->operator<<(static_cast<unsigned long long>(N));
150 raw_ostream &raw_ostream::write_hex(unsigned long long N) {
151 // Zero is a special case.
155 char NumberBuffer[20];
156 char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
157 char *CurPtr = EndPtr;
160 uintptr_t x = N % 16;
161 *--CurPtr = (x < 10 ? '0' + x : 'a' + x - 10);
165 return write(CurPtr, EndPtr-CurPtr);
168 raw_ostream &raw_ostream::operator<<(const void *P) {
171 return write_hex((uintptr_t) P);
174 void raw_ostream::flush_nonempty() {
175 assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty.");
176 size_t Length = OutBufCur - OutBufStart;
177 OutBufCur = OutBufStart;
178 write_impl(OutBufStart, Length);
181 raw_ostream &raw_ostream::write(unsigned char C) {
182 // Group exceptional cases into a single branch.
183 if (BUILTIN_EXPECT(OutBufCur >= OutBufEnd, false)) {
184 if (BUILTIN_EXPECT(!OutBufStart, false)) {
185 if (BufferMode == Unbuffered) {
186 write_impl(reinterpret_cast<char*>(&C), 1);
189 // Set up a buffer and start over.
201 raw_ostream &raw_ostream::write(const char *Ptr, size_t Size) {
202 // Group exceptional cases into a single branch.
203 if (BUILTIN_EXPECT(OutBufCur+Size > OutBufEnd, false)) {
204 if (BUILTIN_EXPECT(!OutBufStart, false)) {
205 if (BufferMode == Unbuffered) {
206 write_impl(Ptr, Size);
209 // Set up a buffer and start over.
211 return write(Ptr, Size);
214 // Write out the data in buffer-sized blocks until the remainder
215 // fits within the buffer.
217 size_t NumBytes = OutBufEnd - OutBufCur;
218 copy_to_buffer(Ptr, NumBytes);
222 } while (OutBufCur+Size > OutBufEnd);
225 copy_to_buffer(Ptr, Size);
230 void raw_ostream::copy_to_buffer(const char *Ptr, size_t Size) {
231 assert(Size <= size_t(OutBufEnd - OutBufCur) && "Buffer overrun!");
233 // Handle short strings specially, memcpy isn't very good at very short
236 case 4: OutBufCur[3] = Ptr[3]; // FALL THROUGH
237 case 3: OutBufCur[2] = Ptr[2]; // FALL THROUGH
238 case 2: OutBufCur[1] = Ptr[1]; // FALL THROUGH
239 case 1: OutBufCur[0] = Ptr[0]; // FALL THROUGH
242 memcpy(OutBufCur, Ptr, Size);
250 raw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) {
251 // If we have more than a few bytes left in our output buffer, try
252 // formatting directly onto its end.
253 size_t NextBufferSize = 127;
254 if (OutBufEnd-OutBufCur > 3) {
255 size_t BufferBytesLeft = OutBufEnd-OutBufCur;
256 size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft);
258 // Common case is that we have plenty of space.
259 if (BytesUsed < BufferBytesLeft) {
260 OutBufCur += BytesUsed;
264 // Otherwise, we overflowed and the return value tells us the size to try
266 NextBufferSize = BytesUsed;
269 // If we got here, we didn't have enough space in the output buffer for the
270 // string. Try printing into a SmallVector that is resized to have enough
271 // space. Iterate until we win.
272 SmallVector<char, 128> V;
275 V.resize(NextBufferSize);
277 // Try formatting into the SmallVector.
278 size_t BytesUsed = Fmt.print(&V[0], NextBufferSize);
280 // If BytesUsed fit into the vector, we win.
281 if (BytesUsed <= NextBufferSize)
282 return write(&V[0], BytesUsed);
284 // Otherwise, try again with a new size.
285 assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?");
286 NextBufferSize = BytesUsed;
290 //===----------------------------------------------------------------------===//
292 //===----------------------------------------------------------------------===//
294 // Out of line virtual method.
295 void format_object_base::home() {
298 //===----------------------------------------------------------------------===//
300 //===----------------------------------------------------------------------===//
302 /// raw_fd_ostream - Open the specified file for writing. If an error
303 /// occurs, information about the error is put into ErrorInfo, and the
304 /// stream should be immediately destroyed; the string will be empty
305 /// if no error occurred.
306 raw_fd_ostream::raw_fd_ostream(const char *Filename, bool Binary, bool Force,
307 std::string &ErrorInfo) : pos(0) {
310 // Handle "-" as stdout.
311 if (Filename[0] == '-' && Filename[1] == 0) {
313 // If user requested binary then put stdout into binary mode if
316 sys::Program::ChangeStdoutToBinary();
321 int Flags = O_WRONLY|O_CREAT|O_TRUNC;
328 FD = open(Filename, Flags, 0664);
330 ErrorInfo = "Error opening output file '" + std::string(Filename) + "'";
337 raw_fd_ostream::~raw_fd_ostream() {
341 if (::close(FD) != 0)
346 void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) {
347 assert (FD >= 0 && "File already closed.");
349 if (::write(FD, Ptr, Size) != (ssize_t) Size)
353 void raw_fd_ostream::close() {
354 assert (ShouldClose);
357 if (::close(FD) != 0)
362 uint64_t raw_fd_ostream::seek(uint64_t off) {
364 pos = ::lseek(FD, off, SEEK_SET);
370 size_t raw_fd_ostream::preferred_buffer_size() {
371 #if !defined(_MSC_VER) && !defined(__MINGW32__) // Windows has no st_blksize.
372 assert(FD >= 0 && "File not yet open!");
374 if (fstat(FD, &statbuf) == 0) {
375 // If this is a terminal, don't use buffering. Line buffering
376 // would be a more traditional thing to do, but it's not worth
378 if (S_ISCHR(statbuf.st_mode) && isatty(FD))
380 // Return the preferred block size.
381 return statbuf.st_blksize;
385 return raw_ostream::preferred_buffer_size();
388 raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold,
390 if (sys::Process::ColorNeedsFlush())
392 const char *colorcode =
393 (colors == SAVEDCOLOR) ? sys::Process::OutputBold(bg)
394 : sys::Process::OutputColor(colors, bold, bg);
396 size_t len = strlen(colorcode);
397 write(colorcode, len);
398 // don't account colors towards output characters
404 raw_ostream &raw_fd_ostream::resetColor() {
405 if (sys::Process::ColorNeedsFlush())
407 const char *colorcode = sys::Process::ResetColor();
409 size_t len = strlen(colorcode);
410 write(colorcode, len);
411 // don't account colors towards output characters
417 //===----------------------------------------------------------------------===//
418 // raw_stdout/err_ostream
419 //===----------------------------------------------------------------------===//
421 // Set buffer settings to model stdout and stderr behavior.
422 // Set standard error to be unbuffered by default.
423 raw_stdout_ostream::raw_stdout_ostream():raw_fd_ostream(STDOUT_FILENO, false) {}
424 raw_stderr_ostream::raw_stderr_ostream():raw_fd_ostream(STDERR_FILENO, false,
427 // An out of line virtual method to provide a home for the class vtable.
428 void raw_stdout_ostream::handle() {}
429 void raw_stderr_ostream::handle() {}
431 /// outs() - This returns a reference to a raw_ostream for standard output.
432 /// Use it like: outs() << "foo" << "bar";
433 raw_ostream &llvm::outs() {
434 static raw_stdout_ostream S;
438 /// errs() - This returns a reference to a raw_ostream for standard error.
439 /// Use it like: errs() << "foo" << "bar";
440 raw_ostream &llvm::errs() {
441 static raw_stderr_ostream S;
445 /// nulls() - This returns a reference to a raw_ostream which discards output.
446 raw_ostream &llvm::nulls() {
447 static raw_null_ostream S;
451 //===----------------------------------------------------------------------===//
453 //===----------------------------------------------------------------------===//
455 raw_os_ostream::~raw_os_ostream() {
459 void raw_os_ostream::write_impl(const char *Ptr, size_t Size) {
463 uint64_t raw_os_ostream::current_pos() { return OS.tellp(); }
465 //===----------------------------------------------------------------------===//
466 // raw_string_ostream
467 //===----------------------------------------------------------------------===//
469 raw_string_ostream::~raw_string_ostream() {
473 void raw_string_ostream::write_impl(const char *Ptr, size_t Size) {
474 OS.append(Ptr, Size);
477 //===----------------------------------------------------------------------===//
478 // raw_svector_ostream
479 //===----------------------------------------------------------------------===//
481 raw_svector_ostream::raw_svector_ostream(SmallVectorImpl<char> &O) : OS(O) {
484 raw_svector_ostream::~raw_svector_ostream() {
488 void raw_svector_ostream::write_impl(const char *Ptr, size_t Size) {
489 OS.append(Ptr, Ptr + Size);
492 uint64_t raw_svector_ostream::current_pos() { return OS.size(); }
494 //===----------------------------------------------------------------------===//
496 //===----------------------------------------------------------------------===//
498 raw_null_ostream::~raw_null_ostream() {
500 // ~raw_ostream asserts that the buffer is empty. This isn't necessary
501 // with raw_null_ostream, but it's better to have raw_null_ostream follow
502 // the rules than to change the rules just for raw_null_ostream.
507 void raw_null_ostream::write_impl(const char *Ptr, size_t Size) {
510 uint64_t raw_null_ostream::current_pos() {