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 SetBufferSize(preferred_buffer_size());
78 void raw_ostream::SetBufferSize(size_t Size
) {
80 "Buffer size must be somewhat large for invariants to hold");
83 delete [] OutBufStart
;
84 OutBufStart
= new char[Size
];
85 OutBufEnd
= OutBufStart
+Size
;
86 OutBufCur
= OutBufStart
;
90 void raw_ostream::SetUnbuffered() {
93 delete [] OutBufStart
;
94 OutBufStart
= OutBufEnd
= OutBufCur
= 0;
98 raw_ostream
&raw_ostream::operator<<(unsigned long N
) {
99 // Zero is a special case.
103 char NumberBuffer
[20];
104 char *EndPtr
= NumberBuffer
+sizeof(NumberBuffer
);
105 char *CurPtr
= EndPtr
;
108 *--CurPtr
= '0' + char(N
% 10);
111 return write(CurPtr
, EndPtr
-CurPtr
);
114 raw_ostream
&raw_ostream::operator<<(long N
) {
120 return this->operator<<(static_cast<unsigned long>(N
));
123 raw_ostream
&raw_ostream::operator<<(unsigned long long N
) {
124 // Output using 32-bit div/mod when possible.
125 if (N
== static_cast<unsigned long>(N
))
126 return this->operator<<(static_cast<unsigned long>(N
));
128 char NumberBuffer
[20];
129 char *EndPtr
= NumberBuffer
+sizeof(NumberBuffer
);
130 char *CurPtr
= EndPtr
;
133 *--CurPtr
= '0' + char(N
% 10);
136 return write(CurPtr
, EndPtr
-CurPtr
);
139 raw_ostream
&raw_ostream::operator<<(long long N
) {
145 return this->operator<<(static_cast<unsigned long long>(N
));
148 raw_ostream
&raw_ostream::write_hex(unsigned long long N
) {
149 // Zero is a special case.
153 char NumberBuffer
[20];
154 char *EndPtr
= NumberBuffer
+sizeof(NumberBuffer
);
155 char *CurPtr
= EndPtr
;
158 uintptr_t x
= N
% 16;
159 *--CurPtr
= (x
< 10 ? '0' + x
: 'a' + x
- 10);
163 return write(CurPtr
, EndPtr
-CurPtr
);
166 raw_ostream
&raw_ostream::operator<<(const void *P
) {
169 return write_hex((uintptr_t) P
);
172 void raw_ostream::flush_nonempty() {
173 assert(OutBufCur
> OutBufStart
&& "Invalid call to flush_nonempty.");
174 write_impl(OutBufStart
, OutBufCur
- OutBufStart
);
175 OutBufCur
= OutBufStart
;
178 raw_ostream
&raw_ostream::write(unsigned char C
) {
179 // Group exceptional cases into a single branch.
180 if (OutBufCur
>= OutBufEnd
) {
182 write_impl(reinterpret_cast<char*>(&C
), 1);
196 raw_ostream
&raw_ostream::write(const char *Ptr
, size_t Size
) {
197 // Group exceptional cases into a single branch.
198 if (BUILTIN_EXPECT(OutBufCur
+Size
> OutBufEnd
, false)) {
199 if (BUILTIN_EXPECT(!OutBufStart
, false)) {
201 write_impl(Ptr
, Size
);
204 // Set up a buffer and start over.
206 return write(Ptr
, Size
);
208 // Write out the data in buffer-sized blocks until the remainder
209 // fits within the buffer.
211 size_t NumBytes
= OutBufEnd
- OutBufCur
;
212 copy_to_buffer(Ptr
, NumBytes
);
216 } while (OutBufCur
+Size
> OutBufEnd
);
219 copy_to_buffer(Ptr
, Size
);
224 void raw_ostream::copy_to_buffer(const char *Ptr
, size_t Size
) {
225 assert(Size
<= size_t(OutBufEnd
- OutBufCur
) && "Buffer overrun!");
227 // Handle short strings specially, memcpy isn't very good at very short
230 case 4: OutBufCur
[3] = Ptr
[3]; // FALL THROUGH
231 case 3: OutBufCur
[2] = Ptr
[2]; // FALL THROUGH
232 case 2: OutBufCur
[1] = Ptr
[1]; // FALL THROUGH
233 case 1: OutBufCur
[0] = Ptr
[0]; // FALL THROUGH
236 memcpy(OutBufCur
, Ptr
, Size
);
244 raw_ostream
&raw_ostream::operator<<(const format_object_base
&Fmt
) {
245 // If we have more than a few bytes left in our output buffer, try
246 // formatting directly onto its end.
248 // FIXME: This test is a bit silly, since if we don't have enough
249 // space in the buffer we will have to flush the formatted output
250 // anyway. We should just flush upfront in such cases, and use the
251 // whole buffer as our scratch pad. Note, however, that this case is
252 // also necessary for correctness on unbuffered streams.
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();
318 // Mimic stdout by defaulting to unbuffered if the output device
320 if (sys::Process::StandardOutIsDisplayed())
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 return statbuf
.st_blksize
;
382 return raw_ostream::preferred_buffer_size();
385 raw_ostream
&raw_fd_ostream::changeColor(enum Colors colors
, bool bold
,
387 if (sys::Process::ColorNeedsFlush())
389 const char *colorcode
=
390 (colors
== SAVEDCOLOR
) ? sys::Process::OutputBold(bg
)
391 : sys::Process::OutputColor(colors
, bold
, bg
);
393 size_t len
= strlen(colorcode
);
394 write(colorcode
, len
);
395 // don't account colors towards output characters
401 raw_ostream
&raw_fd_ostream::resetColor() {
402 if (sys::Process::ColorNeedsFlush())
404 const char *colorcode
= sys::Process::ResetColor();
406 size_t len
= strlen(colorcode
);
407 write(colorcode
, len
);
408 // don't account colors towards output characters
414 //===----------------------------------------------------------------------===//
415 // raw_stdout/err_ostream
416 //===----------------------------------------------------------------------===//
418 // Set buffer settings to model stdout and stderr behavior.
419 // raw_ostream doesn't support line buffering, so set standard output to be
420 // unbuffered when the output device is a terminal. Set standard error to
422 raw_stdout_ostream::raw_stdout_ostream()
423 : raw_fd_ostream(STDOUT_FILENO
, false,
424 sys::Process::StandardOutIsDisplayed()) {}
425 raw_stderr_ostream::raw_stderr_ostream():raw_fd_ostream(STDERR_FILENO
, false,
428 // An out of line virtual method to provide a home for the class vtable.
429 void raw_stdout_ostream::handle() {}
430 void raw_stderr_ostream::handle() {}
432 /// outs() - This returns a reference to a raw_ostream for standard output.
433 /// Use it like: outs() << "foo" << "bar";
434 raw_ostream
&llvm::outs() {
435 static raw_stdout_ostream S
;
439 /// errs() - This returns a reference to a raw_ostream for standard error.
440 /// Use it like: errs() << "foo" << "bar";
441 raw_ostream
&llvm::errs() {
442 static raw_stderr_ostream S
;
446 /// nulls() - This returns a reference to a raw_ostream which discards output.
447 raw_ostream
&llvm::nulls() {
448 static raw_null_ostream S
;
452 //===----------------------------------------------------------------------===//
454 //===----------------------------------------------------------------------===//
456 void raw_os_ostream::write_impl(const char *Ptr
, size_t Size
) {
460 uint64_t raw_os_ostream::current_pos() { return OS
.tellp(); }
462 uint64_t raw_os_ostream::tell() {
463 return (uint64_t)OS
.tellp() + GetNumBytesInBuffer();
466 //===----------------------------------------------------------------------===//
467 // raw_string_ostream
468 //===----------------------------------------------------------------------===//
470 void raw_string_ostream::write_impl(const char *Ptr
, size_t Size
) {
471 OS
.append(Ptr
, Size
);
474 //===----------------------------------------------------------------------===//
475 // raw_svector_ostream
476 //===----------------------------------------------------------------------===//
478 void raw_svector_ostream::write_impl(const char *Ptr
, size_t Size
) {
479 OS
.append(Ptr
, Ptr
+ Size
);
482 uint64_t raw_svector_ostream::current_pos() { return OS
.size(); }
484 uint64_t raw_svector_ostream::tell() {
485 return OS
.size() + GetNumBytesInBuffer();
488 //===----------------------------------------------------------------------===//
490 //===----------------------------------------------------------------------===//
492 raw_null_ostream::~raw_null_ostream() {
494 // ~raw_ostream asserts that the buffer is empty. This isn't necessary
495 // with raw_null_ostream, but it's better to have raw_null_ostream follow
496 // the rules than to change the rules just for raw_null_ostream.
501 void raw_null_ostream::write_impl(const char *Ptr
, size_t Size
) {
504 uint64_t raw_null_ostream::current_pos() {