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"
23 #include "llvm/ADT/StringExtras.h"
25 #include <sys/types.h>
27 #if defined(HAVE_UNISTD_H)
30 #if defined(HAVE_FCNTL_H)
38 # define STDIN_FILENO 0
41 # define STDOUT_FILENO 1
44 # define STDERR_FILENO 2
50 raw_ostream::~raw_ostream() {
51 // raw_ostream's subclasses should take care to flush the buffer
52 // in their destructors.
53 assert(OutBufCur
== OutBufStart
&&
54 "raw_ostream destructor called with non-empty buffer!");
56 if (BufferMode
== InternalBuffer
)
57 delete [] OutBufStart
;
59 // If there are any pending errors, report them now. Clients wishing
60 // to avoid llvm_report_error calls should check for errors with
61 // has_error() and clear the error flag with clear_error() before
62 // destructing raw_ostream objects which may have errors.
64 llvm_report_error("IO failure on output stream.");
67 // An out of line virtual method to provide a home for the class vtable.
68 void raw_ostream::handle() {}
70 size_t raw_ostream::preferred_buffer_size() {
71 // BUFSIZ is intended to be a reasonable default.
75 void raw_ostream::SetBuffered() {
76 // Ask the subclass to determine an appropriate buffer size.
77 if (size_t Size
= preferred_buffer_size())
80 // It may return 0, meaning this stream should be unbuffered.
84 void raw_ostream::SetBufferAndMode(char *BufferStart
, size_t Size
,
86 assert(((Mode
== Unbuffered
&& BufferStart
== 0 && Size
== 0) ||
87 (Mode
!= Unbuffered
&& BufferStart
&& Size
>= 64)) &&
88 "stream must be unbuffered, or have >= 64 bytes of buffer");
89 // Make sure the current buffer is free of content (we can't flush here; the
90 // child buffer management logic will be in write_impl).
91 assert(GetNumBytesInBuffer() == 0 && "Current buffer is non-empty!");
93 if (BufferMode
== InternalBuffer
)
94 delete [] OutBufStart
;
95 OutBufStart
= BufferStart
;
96 OutBufEnd
= OutBufStart
+Size
;
97 OutBufCur
= OutBufStart
;
100 assert(OutBufStart
<= OutBufEnd
&& "Invalid size!");
103 raw_ostream
&raw_ostream::operator<<(unsigned long N
) {
104 // Zero is a special case.
108 char NumberBuffer
[20];
109 char *EndPtr
= NumberBuffer
+sizeof(NumberBuffer
);
110 char *CurPtr
= EndPtr
;
113 *--CurPtr
= '0' + char(N
% 10);
116 return write(CurPtr
, EndPtr
-CurPtr
);
119 raw_ostream
&raw_ostream::operator<<(long N
) {
125 return this->operator<<(static_cast<unsigned long>(N
));
128 raw_ostream
&raw_ostream::operator<<(unsigned long long N
) {
129 // Output using 32-bit div/mod when possible.
130 if (N
== static_cast<unsigned long>(N
))
131 return this->operator<<(static_cast<unsigned long>(N
));
133 char NumberBuffer
[20];
134 char *EndPtr
= NumberBuffer
+sizeof(NumberBuffer
);
135 char *CurPtr
= EndPtr
;
138 *--CurPtr
= '0' + char(N
% 10);
141 return write(CurPtr
, EndPtr
-CurPtr
);
144 raw_ostream
&raw_ostream::operator<<(long long N
) {
150 return this->operator<<(static_cast<unsigned long long>(N
));
153 raw_ostream
&raw_ostream::write_hex(unsigned long long N
) {
154 // Zero is a special case.
158 char NumberBuffer
[20];
159 char *EndPtr
= NumberBuffer
+sizeof(NumberBuffer
);
160 char *CurPtr
= EndPtr
;
163 uintptr_t x
= N
% 16;
164 *--CurPtr
= (x
< 10 ? '0' + x
: 'a' + x
- 10);
168 return write(CurPtr
, EndPtr
-CurPtr
);
171 raw_ostream
&raw_ostream::operator<<(const void *P
) {
174 return write_hex((uintptr_t) P
);
177 raw_ostream
&raw_ostream::operator<<(double N
) {
178 this->operator<<(ftostr(N
));
184 void raw_ostream::flush_nonempty() {
185 assert(OutBufCur
> OutBufStart
&& "Invalid call to flush_nonempty.");
186 size_t Length
= OutBufCur
- OutBufStart
;
187 OutBufCur
= OutBufStart
;
188 write_impl(OutBufStart
, Length
);
191 raw_ostream
&raw_ostream::write(unsigned char C
) {
192 // Group exceptional cases into a single branch.
193 if (BUILTIN_EXPECT(OutBufCur
>= OutBufEnd
, false)) {
194 if (BUILTIN_EXPECT(!OutBufStart
, false)) {
195 if (BufferMode
== Unbuffered
) {
196 write_impl(reinterpret_cast<char*>(&C
), 1);
199 // Set up a buffer and start over.
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
);
224 // Write out the data in buffer-sized blocks until the remainder
225 // fits within the buffer.
227 size_t NumBytes
= OutBufEnd
- OutBufCur
;
228 copy_to_buffer(Ptr
, NumBytes
);
232 } while (OutBufCur
+Size
> OutBufEnd
);
235 copy_to_buffer(Ptr
, Size
);
240 void raw_ostream::copy_to_buffer(const char *Ptr
, size_t Size
) {
241 assert(Size
<= size_t(OutBufEnd
- OutBufCur
) && "Buffer overrun!");
243 // Handle short strings specially, memcpy isn't very good at very short
246 case 4: OutBufCur
[3] = Ptr
[3]; // FALL THROUGH
247 case 3: OutBufCur
[2] = Ptr
[2]; // FALL THROUGH
248 case 2: OutBufCur
[1] = Ptr
[1]; // FALL THROUGH
249 case 1: OutBufCur
[0] = Ptr
[0]; // FALL THROUGH
252 memcpy(OutBufCur
, Ptr
, Size
);
260 raw_ostream
&raw_ostream::operator<<(const format_object_base
&Fmt
) {
261 // If we have more than a few bytes left in our output buffer, try
262 // formatting directly onto its end.
263 size_t NextBufferSize
= 127;
264 size_t BufferBytesLeft
= OutBufEnd
- OutBufCur
;
265 if (BufferBytesLeft
> 3) {
266 size_t BytesUsed
= Fmt
.print(OutBufCur
, BufferBytesLeft
);
268 // Common case is that we have plenty of space.
269 if (BytesUsed
<= BufferBytesLeft
) {
270 OutBufCur
+= BytesUsed
;
274 // Otherwise, we overflowed and the return value tells us the size to try
276 NextBufferSize
= BytesUsed
;
279 // If we got here, we didn't have enough space in the output buffer for the
280 // string. Try printing into a SmallVector that is resized to have enough
281 // space. Iterate until we win.
282 SmallVector
<char, 128> V
;
285 V
.resize(NextBufferSize
);
287 // Try formatting into the SmallVector.
288 size_t BytesUsed
= Fmt
.print(V
.data(), NextBufferSize
);
290 // If BytesUsed fit into the vector, we win.
291 if (BytesUsed
<= NextBufferSize
)
292 return write(V
.data(), BytesUsed
);
294 // Otherwise, try again with a new size.
295 assert(BytesUsed
> NextBufferSize
&& "Didn't grow buffer!?");
296 NextBufferSize
= BytesUsed
;
300 /// indent - Insert 'NumSpaces' spaces.
301 raw_ostream
&raw_ostream::indent(unsigned NumSpaces
) {
302 static const char Spaces
[] = " "
306 // Usually the indentation is small, handle it with a fastpath.
307 if (NumSpaces
< array_lengthof(Spaces
))
308 return write(Spaces
, NumSpaces
);
311 unsigned NumToWrite
= std::min(NumSpaces
,
312 (unsigned)array_lengthof(Spaces
)-1);
313 write(Spaces
, NumToWrite
);
314 NumSpaces
-= NumToWrite
;
320 //===----------------------------------------------------------------------===//
322 //===----------------------------------------------------------------------===//
324 // Out of line virtual method.
325 void format_object_base::home() {
328 //===----------------------------------------------------------------------===//
330 //===----------------------------------------------------------------------===//
332 /// raw_fd_ostream - Open the specified file for writing. If an error
333 /// occurs, information about the error is put into ErrorInfo, and the
334 /// stream should be immediately destroyed; the string will be empty
335 /// if no error occurred.
336 raw_fd_ostream::raw_fd_ostream(const char *Filename
, std::string
&ErrorInfo
,
337 unsigned Flags
) : pos(0) {
338 // Verify that we don't have both "append" and "excl".
339 assert((!(Flags
& F_Excl
) || !(Flags
& F_Append
)) &&
340 "Cannot specify both 'excl' and 'append' file creation flags!");
344 // Handle "-" as stdout.
345 if (Filename
[0] == '-' && Filename
[1] == 0) {
347 // If user requested binary then put stdout into binary mode if
349 if (Flags
& F_Binary
)
350 sys::Program::ChangeStdoutToBinary();
355 int OpenFlags
= O_WRONLY
|O_CREAT
;
357 if (Flags
& F_Binary
)
358 OpenFlags
|= O_BINARY
;
361 if (Flags
& F_Append
)
362 OpenFlags
|= O_APPEND
;
364 OpenFlags
|= O_TRUNC
;
368 FD
= open(Filename
, OpenFlags
, 0664);
370 ErrorInfo
= "Error opening output file '" + std::string(Filename
) + "'";
377 raw_fd_ostream::~raw_fd_ostream() {
381 if (::close(FD
) != 0)
386 void raw_fd_ostream::write_impl(const char *Ptr
, size_t Size
) {
387 assert (FD
>= 0 && "File already closed.");
389 if (::write(FD
, Ptr
, Size
) != (ssize_t
) Size
)
393 void raw_fd_ostream::close() {
394 assert (ShouldClose
);
397 if (::close(FD
) != 0)
402 uint64_t raw_fd_ostream::seek(uint64_t off
) {
404 pos
= ::lseek(FD
, off
, SEEK_SET
);
410 size_t raw_fd_ostream::preferred_buffer_size() {
411 #if !defined(_MSC_VER) && !defined(__MINGW32__) // Windows has no st_blksize.
412 assert(FD
>= 0 && "File not yet open!");
414 if (fstat(FD
, &statbuf
) == 0) {
415 // If this is a terminal, don't use buffering. Line buffering
416 // would be a more traditional thing to do, but it's not worth
418 if (S_ISCHR(statbuf
.st_mode
) && isatty(FD
))
420 // Return the preferred block size.
421 return statbuf
.st_blksize
;
425 return raw_ostream::preferred_buffer_size();
428 raw_ostream
&raw_fd_ostream::changeColor(enum Colors colors
, bool bold
,
430 if (sys::Process::ColorNeedsFlush())
432 const char *colorcode
=
433 (colors
== SAVEDCOLOR
) ? sys::Process::OutputBold(bg
)
434 : sys::Process::OutputColor(colors
, bold
, bg
);
436 size_t len
= strlen(colorcode
);
437 write(colorcode
, len
);
438 // don't account colors towards output characters
444 raw_ostream
&raw_fd_ostream::resetColor() {
445 if (sys::Process::ColorNeedsFlush())
447 const char *colorcode
= sys::Process::ResetColor();
449 size_t len
= strlen(colorcode
);
450 write(colorcode
, len
);
451 // don't account colors towards output characters
457 //===----------------------------------------------------------------------===//
458 // raw_stdout/err_ostream
459 //===----------------------------------------------------------------------===//
461 // Set buffer settings to model stdout and stderr behavior.
462 // Set standard error to be unbuffered by default.
463 raw_stdout_ostream::raw_stdout_ostream():raw_fd_ostream(STDOUT_FILENO
, false) {}
464 raw_stderr_ostream::raw_stderr_ostream():raw_fd_ostream(STDERR_FILENO
, false,
467 // An out of line virtual method to provide a home for the class vtable.
468 void raw_stdout_ostream::handle() {}
469 void raw_stderr_ostream::handle() {}
471 /// outs() - This returns a reference to a raw_ostream for standard output.
472 /// Use it like: outs() << "foo" << "bar";
473 raw_ostream
&llvm::outs() {
474 static raw_stdout_ostream S
;
478 /// errs() - This returns a reference to a raw_ostream for standard error.
479 /// Use it like: errs() << "foo" << "bar";
480 raw_ostream
&llvm::errs() {
481 static raw_stderr_ostream S
;
485 /// nulls() - This returns a reference to a raw_ostream which discards output.
486 raw_ostream
&llvm::nulls() {
487 static raw_null_ostream S
;
492 //===----------------------------------------------------------------------===//
493 // raw_string_ostream
494 //===----------------------------------------------------------------------===//
496 raw_string_ostream::~raw_string_ostream() {
500 void raw_string_ostream::write_impl(const char *Ptr
, size_t Size
) {
501 OS
.append(Ptr
, Size
);
504 //===----------------------------------------------------------------------===//
505 // raw_svector_ostream
506 //===----------------------------------------------------------------------===//
508 // The raw_svector_ostream implementation uses the SmallVector itself as the
509 // buffer for the raw_ostream. We guarantee that the raw_ostream buffer is
510 // always pointing past the end of the vector, but within the vector
511 // capacity. This allows raw_ostream to write directly into the correct place,
512 // and we only need to set the vector size when the data is flushed.
514 raw_svector_ostream::raw_svector_ostream(SmallVectorImpl
<char> &O
) : OS(O
) {
515 // Set up the initial external buffer. We make sure that the buffer has at
516 // least 128 bytes free; raw_ostream itself only requires 64, but we want to
517 // make sure that we don't grow the buffer unnecessarily on destruction (when
518 // the data is flushed). See the FIXME below.
519 OS
.reserve(OS
.size() + 128);
520 SetBuffer(OS
.end(), OS
.capacity() - OS
.size());
523 raw_svector_ostream::~raw_svector_ostream() {
524 // FIXME: Prevent resizing during this flush().
528 void raw_svector_ostream::write_impl(const char *Ptr
, size_t Size
) {
529 assert(Ptr
== OS
.end() && OS
.size() + Size
<= OS
.capacity() &&
530 "Invalid write_impl() call!");
532 // We don't need to copy the bytes, just commit the bytes to the
534 OS
.set_size(OS
.size() + Size
);
536 // Grow the vector if necessary.
537 if (OS
.capacity() - OS
.size() < 64)
538 OS
.reserve(OS
.capacity() * 2);
540 // Update the buffer position.
541 SetBuffer(OS
.end(), OS
.capacity() - OS
.size());
544 uint64_t raw_svector_ostream::current_pos() { return OS
.size(); }
546 StringRef
raw_svector_ostream::str() {
548 return StringRef(OS
.begin(), OS
.size());
551 //===----------------------------------------------------------------------===//
553 //===----------------------------------------------------------------------===//
555 raw_null_ostream::~raw_null_ostream() {
557 // ~raw_ostream asserts that the buffer is empty. This isn't necessary
558 // with raw_null_ostream, but it's better to have raw_null_ostream follow
559 // the rules than to change the rules just for raw_null_ostream.
564 void raw_null_ostream::write_impl(const char *Ptr
, size_t Size
) {
567 uint64_t raw_null_ostream::current_pos() {