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 delete [] OutBufStart;
57 // If there are any pending errors, report them now. Clients wishing
58 // to avoid llvm_report_error calls should check for errors with
59 // has_error() and clear the error flag with clear_error() before
60 // destructing raw_ostream objects which may have errors.
62 llvm_report_error("IO failure on output stream.");
65 // An out of line virtual method to provide a home for the class vtable.
66 void raw_ostream::handle() {}
68 size_t raw_ostream::preferred_buffer_size() {
69 // BUFSIZ is intended to be a reasonable default.
73 void raw_ostream::SetBuffered() {
74 // Ask the subclass to determine an appropriate buffer size.
75 if (size_t Size = preferred_buffer_size())
78 // It may return 0, meaning this stream should be unbuffered.
82 void raw_ostream::SetBufferSize(size_t Size) {
84 "Buffer size must be somewhat large for invariants to hold");
87 delete [] OutBufStart;
88 OutBufStart = new char[Size];
89 OutBufEnd = OutBufStart+Size;
90 OutBufCur = OutBufStart;
94 void raw_ostream::SetUnbuffered() {
97 delete [] OutBufStart;
98 OutBufStart = OutBufEnd = OutBufCur = 0;
102 raw_ostream &raw_ostream::operator<<(unsigned long N) {
103 // Zero is a special case.
107 char NumberBuffer[20];
108 char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
109 char *CurPtr = EndPtr;
112 *--CurPtr = '0' + char(N % 10);
115 return write(CurPtr, EndPtr-CurPtr);
118 raw_ostream &raw_ostream::operator<<(long N) {
124 return this->operator<<(static_cast<unsigned long>(N));
127 raw_ostream &raw_ostream::operator<<(unsigned long long N) {
128 // Output using 32-bit div/mod when possible.
129 if (N == static_cast<unsigned long>(N))
130 return this->operator<<(static_cast<unsigned long>(N));
132 char NumberBuffer[20];
133 char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
134 char *CurPtr = EndPtr;
137 *--CurPtr = '0' + char(N % 10);
140 return write(CurPtr, EndPtr-CurPtr);
143 raw_ostream &raw_ostream::operator<<(long long N) {
149 return this->operator<<(static_cast<unsigned long long>(N));
152 raw_ostream &raw_ostream::write_hex(unsigned long long N) {
153 // Zero is a special case.
157 char NumberBuffer[20];
158 char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
159 char *CurPtr = EndPtr;
162 uintptr_t x = N % 16;
163 *--CurPtr = (x < 10 ? '0' + x : 'a' + x - 10);
167 return write(CurPtr, EndPtr-CurPtr);
170 raw_ostream &raw_ostream::operator<<(const void *P) {
173 return write_hex((uintptr_t) P);
176 void raw_ostream::flush_nonempty() {
177 assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty.");
178 write_impl(OutBufStart, OutBufCur - OutBufStart);
179 OutBufCur = OutBufStart;
182 raw_ostream &raw_ostream::write(unsigned char C) {
183 // Group exceptional cases into a single branch.
184 if (OutBufCur >= OutBufEnd) {
186 write_impl(reinterpret_cast<char*>(&C), 1);
200 raw_ostream &raw_ostream::write(const char *Ptr, size_t Size) {
201 // Group exceptional cases into a single branch.
202 if (BUILTIN_EXPECT(OutBufCur+Size > OutBufEnd, false)) {
203 if (BUILTIN_EXPECT(!OutBufStart, false)) {
205 write_impl(Ptr, Size);
208 // Set up a buffer and start over.
210 return write(Ptr, Size);
212 // Write out the data in buffer-sized blocks until the remainder
213 // fits within the buffer.
215 size_t NumBytes = OutBufEnd - OutBufCur;
216 copy_to_buffer(Ptr, NumBytes);
220 } while (OutBufCur+Size > OutBufEnd);
223 copy_to_buffer(Ptr, Size);
228 void raw_ostream::copy_to_buffer(const char *Ptr, size_t Size) {
229 assert(Size <= size_t(OutBufEnd - OutBufCur) && "Buffer overrun!");
231 // Handle short strings specially, memcpy isn't very good at very short
234 case 4: OutBufCur[3] = Ptr[3]; // FALL THROUGH
235 case 3: OutBufCur[2] = Ptr[2]; // FALL THROUGH
236 case 2: OutBufCur[1] = Ptr[1]; // FALL THROUGH
237 case 1: OutBufCur[0] = Ptr[0]; // FALL THROUGH
240 memcpy(OutBufCur, Ptr, Size);
248 raw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) {
249 // If we have more than a few bytes left in our output buffer, try
250 // formatting directly onto its end.
252 // FIXME: This test is a bit silly, since if we don't have enough
253 // space in the buffer we will have to flush the formatted output
254 // anyway. We should just flush upfront in such cases, and use the
255 // whole buffer as our scratch pad. Note, however, that this case is
256 // also necessary for correctness on unbuffered streams.
257 size_t NextBufferSize = 127;
258 if (OutBufEnd-OutBufCur > 3) {
259 size_t BufferBytesLeft = OutBufEnd-OutBufCur;
260 size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft);
262 // Common case is that we have plenty of space.
263 if (BytesUsed < BufferBytesLeft) {
264 OutBufCur += BytesUsed;
268 // Otherwise, we overflowed and the return value tells us the size to try
270 NextBufferSize = BytesUsed;
273 // If we got here, we didn't have enough space in the output buffer for the
274 // string. Try printing into a SmallVector that is resized to have enough
275 // space. Iterate until we win.
276 SmallVector<char, 128> V;
279 V.resize(NextBufferSize);
281 // Try formatting into the SmallVector.
282 size_t BytesUsed = Fmt.print(&V[0], NextBufferSize);
284 // If BytesUsed fit into the vector, we win.
285 if (BytesUsed <= NextBufferSize)
286 return write(&V[0], BytesUsed);
288 // Otherwise, try again with a new size.
289 assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?");
290 NextBufferSize = BytesUsed;
294 //===----------------------------------------------------------------------===//
296 //===----------------------------------------------------------------------===//
298 // Out of line virtual method.
299 void format_object_base::home() {
302 //===----------------------------------------------------------------------===//
304 //===----------------------------------------------------------------------===//
306 /// raw_fd_ostream - Open the specified file for writing. If an error
307 /// occurs, information about the error is put into ErrorInfo, and the
308 /// stream should be immediately destroyed; the string will be empty
309 /// if no error occurred.
310 raw_fd_ostream::raw_fd_ostream(const char *Filename, bool Binary, bool Force,
311 std::string &ErrorInfo) : pos(0) {
314 // Handle "-" as stdout.
315 if (Filename[0] == '-' && Filename[1] == 0) {
317 // If user requested binary then put stdout into binary mode if
320 sys::Program::ChangeStdoutToBinary();
325 int Flags = O_WRONLY|O_CREAT|O_TRUNC;
332 FD = open(Filename, Flags, 0664);
334 ErrorInfo = "Error opening output file '" + std::string(Filename) + "'";
341 raw_fd_ostream::~raw_fd_ostream() {
345 if (::close(FD) != 0)
350 void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) {
351 assert (FD >= 0 && "File already closed.");
353 if (::write(FD, Ptr, Size) != (ssize_t) Size)
357 void raw_fd_ostream::close() {
358 assert (ShouldClose);
361 if (::close(FD) != 0)
366 uint64_t raw_fd_ostream::seek(uint64_t off) {
368 pos = ::lseek(FD, off, SEEK_SET);
374 size_t raw_fd_ostream::preferred_buffer_size() {
375 #if !defined(_MSC_VER) // Windows reportedly doesn't have st_blksize.
376 assert(FD >= 0 && "File not yet open!");
378 if (fstat(FD, &statbuf) == 0) {
379 // If this is a terminal, don't use buffering. Line buffering
380 // would be a more traditional thing to do, but it's not worth
382 if (S_ISCHR(statbuf.st_mode) && isatty(FD))
384 // Return the preferred block size.
385 return statbuf.st_blksize;
389 return raw_ostream::preferred_buffer_size();
392 raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold,
394 if (sys::Process::ColorNeedsFlush())
396 const char *colorcode =
397 (colors == SAVEDCOLOR) ? sys::Process::OutputBold(bg)
398 : sys::Process::OutputColor(colors, bold, bg);
400 size_t len = strlen(colorcode);
401 write(colorcode, len);
402 // don't account colors towards output characters
408 raw_ostream &raw_fd_ostream::resetColor() {
409 if (sys::Process::ColorNeedsFlush())
411 const char *colorcode = sys::Process::ResetColor();
413 size_t len = strlen(colorcode);
414 write(colorcode, len);
415 // don't account colors towards output characters
421 //===----------------------------------------------------------------------===//
422 // raw_stdout/err_ostream
423 //===----------------------------------------------------------------------===//
425 // Set buffer settings to model stdout and stderr behavior.
426 // Set standard error to be unbuffered by default.
427 raw_stdout_ostream::raw_stdout_ostream():raw_fd_ostream(STDOUT_FILENO, false) {}
428 raw_stderr_ostream::raw_stderr_ostream():raw_fd_ostream(STDERR_FILENO, false,
431 // An out of line virtual method to provide a home for the class vtable.
432 void raw_stdout_ostream::handle() {}
433 void raw_stderr_ostream::handle() {}
435 /// outs() - This returns a reference to a raw_ostream for standard output.
436 /// Use it like: outs() << "foo" << "bar";
437 raw_ostream &llvm::outs() {
438 static raw_stdout_ostream S;
442 /// errs() - This returns a reference to a raw_ostream for standard error.
443 /// Use it like: errs() << "foo" << "bar";
444 raw_ostream &llvm::errs() {
445 static raw_stderr_ostream S;
449 /// nulls() - This returns a reference to a raw_ostream which discards output.
450 raw_ostream &llvm::nulls() {
451 static raw_null_ostream S;
455 //===----------------------------------------------------------------------===//
457 //===----------------------------------------------------------------------===//
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 uint64_t raw_os_ostream::tell() {
466 return (uint64_t)OS.tellp() + GetNumBytesInBuffer();
469 //===----------------------------------------------------------------------===//
470 // raw_string_ostream
471 //===----------------------------------------------------------------------===//
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 void raw_svector_ostream::write_impl(const char *Ptr, size_t Size) {
482 OS.append(Ptr, Ptr + Size);
485 uint64_t raw_svector_ostream::current_pos() { return OS.size(); }
487 uint64_t raw_svector_ostream::tell() {
488 return OS.size() + GetNumBytesInBuffer();
491 //===----------------------------------------------------------------------===//
493 //===----------------------------------------------------------------------===//
495 raw_null_ostream::~raw_null_ostream() {
497 // ~raw_ostream asserts that the buffer is empty. This isn't necessary
498 // with raw_null_ostream, but it's better to have raw_null_ostream follow
499 // the rules than to change the rules just for raw_null_ostream.
504 void raw_null_ostream::write_impl(const char *Ptr, size_t Size) {
507 uint64_t raw_null_ostream::current_pos() {