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 #if defined(HAVE_UNISTD_H)
27 #if defined(HAVE_FCNTL_H)
35 # define STDIN_FILENO 0
38 # define STDOUT_FILENO 1
41 # define STDERR_FILENO 2
47 raw_ostream::~raw_ostream() {
48 delete [] OutBufStart
;
50 // If there are any pending errors, report them now. Clients wishing
51 // to avoid llvm_report_error calls should check for errors with
52 // has_error() and clear the error flag with clear_error() before
53 // destructing raw_ostream objects which may have errors.
55 llvm_report_error("IO failure on output stream.");
58 // An out of line virtual method to provide a home for the class vtable.
59 void raw_ostream::handle() {}
61 raw_ostream
&raw_ostream::operator<<(unsigned long N
) {
62 // Zero is a special case.
66 char NumberBuffer
[20];
67 char *EndPtr
= NumberBuffer
+sizeof(NumberBuffer
);
68 char *CurPtr
= EndPtr
;
71 *--CurPtr
= '0' + char(N
% 10);
74 return write(CurPtr
, EndPtr
-CurPtr
);
77 raw_ostream
&raw_ostream::operator<<(long N
) {
83 return this->operator<<(static_cast<unsigned long>(N
));
86 raw_ostream
&raw_ostream::operator<<(unsigned long long N
) {
87 // Zero is a special case.
91 char NumberBuffer
[20];
92 char *EndPtr
= NumberBuffer
+sizeof(NumberBuffer
);
93 char *CurPtr
= EndPtr
;
96 *--CurPtr
= '0' + char(N
% 10);
99 return write(CurPtr
, EndPtr
-CurPtr
);
102 raw_ostream
&raw_ostream::operator<<(long long N
) {
108 return this->operator<<(static_cast<unsigned long long>(N
));
111 raw_ostream
&raw_ostream::operator<<(const void *P
) {
112 uintptr_t N
= (uintptr_t) P
;
115 // Zero is a special case.
119 char NumberBuffer
[20];
120 char *EndPtr
= NumberBuffer
+sizeof(NumberBuffer
);
121 char *CurPtr
= EndPtr
;
125 *--CurPtr
= (x
< 10 ? '0' + x
: 'a' + x
- 10);
129 return write(CurPtr
, EndPtr
-CurPtr
);
132 void raw_ostream::flush_nonempty() {
133 assert(OutBufCur
> OutBufStart
&& "Invalid call to flush_nonempty.");
134 write_impl(OutBufStart
, OutBufCur
- OutBufStart
);
135 OutBufCur
= OutBufStart
;
138 raw_ostream
&raw_ostream::write(unsigned char C
) {
139 // Group exceptional cases into a single branch.
140 if (OutBufCur
>= OutBufEnd
) {
142 write_impl(reinterpret_cast<char*>(&C
), 1);
156 raw_ostream
&raw_ostream::write(const char *Ptr
, unsigned Size
) {
157 // Group exceptional cases into a single branch.
158 if (BUILTIN_EXPECT(OutBufCur
+Size
> OutBufEnd
, false)) {
160 write_impl(Ptr
, Size
);
170 // Handle short strings specially, memcpy isn't very good at very short
173 case 4: OutBufCur
[3] = Ptr
[3]; // FALL THROUGH
174 case 3: OutBufCur
[2] = Ptr
[2]; // FALL THROUGH
175 case 2: OutBufCur
[1] = Ptr
[1]; // FALL THROUGH
176 case 1: OutBufCur
[0] = Ptr
[0]; // FALL THROUGH
179 // Normally the string to emit is shorter than the buffer.
180 if (Size
<= unsigned(OutBufEnd
-OutBufCur
)) {
181 memcpy(OutBufCur
, Ptr
, Size
);
185 // Otherwise we are emitting a string larger than our buffer. We
186 // know we already flushed, so just write it out directly.
187 write_impl(Ptr
, Size
);
197 raw_ostream
&raw_ostream::operator<<(const format_object_base
&Fmt
) {
198 // If we have more than a few bytes left in our output buffer, try
199 // formatting directly onto its end.
201 // FIXME: This test is a bit silly, since if we don't have enough
202 // space in the buffer we will have to flush the formatted output
203 // anyway. We should just flush upfront in such cases, and use the
204 // whole buffer as our scratch pad. Note, however, that this case is
205 // also necessary for correctness on unbuffered streams.
206 unsigned NextBufferSize
= 127;
207 if (OutBufEnd
-OutBufCur
> 3) {
208 unsigned BufferBytesLeft
= OutBufEnd
-OutBufCur
;
209 unsigned BytesUsed
= Fmt
.print(OutBufCur
, BufferBytesLeft
);
211 // Common case is that we have plenty of space.
212 if (BytesUsed
< BufferBytesLeft
) {
213 OutBufCur
+= BytesUsed
;
217 // Otherwise, we overflowed and the return value tells us the size to try
219 NextBufferSize
= BytesUsed
;
222 // If we got here, we didn't have enough space in the output buffer for the
223 // string. Try printing into a SmallVector that is resized to have enough
224 // space. Iterate until we win.
225 SmallVector
<char, 128> V
;
228 V
.resize(NextBufferSize
);
230 // Try formatting into the SmallVector.
231 unsigned BytesUsed
= Fmt
.print(&V
[0], NextBufferSize
);
233 // If BytesUsed fit into the vector, we win.
234 if (BytesUsed
<= NextBufferSize
)
235 return write(&V
[0], BytesUsed
);
237 // Otherwise, try again with a new size.
238 assert(BytesUsed
> NextBufferSize
&& "Didn't grow buffer!?");
239 NextBufferSize
= BytesUsed
;
243 //===----------------------------------------------------------------------===//
245 //===----------------------------------------------------------------------===//
247 // Out of line virtual method.
248 void format_object_base::home() {
251 //===----------------------------------------------------------------------===//
253 //===----------------------------------------------------------------------===//
255 /// raw_fd_ostream - Open the specified file for writing. If an error
256 /// occurs, information about the error is put into ErrorInfo, and the
257 /// stream should be immediately destroyed; the string will be empty
258 /// if no error occurred.
259 raw_fd_ostream::raw_fd_ostream(const char *Filename
, bool Binary
, bool Force
,
260 std::string
&ErrorInfo
) : pos(0) {
263 // Handle "-" as stdout.
264 if (Filename
[0] == '-' && Filename
[1] == 0) {
266 // If user requested binary then put stdout into binary mode if
269 sys::Program::ChangeStdoutToBinary();
274 int Flags
= O_WRONLY
|O_CREAT
|O_TRUNC
;
281 FD
= open(Filename
, Flags
, 0664);
283 ErrorInfo
= "Error opening output file '" + std::string(Filename
) + "'";
290 raw_fd_ostream::~raw_fd_ostream() {
294 if (::close(FD
) != 0)
299 void raw_fd_ostream::write_impl(const char *Ptr
, unsigned Size
) {
300 assert (FD
>= 0 && "File already closed.");
302 if (::write(FD
, Ptr
, Size
) != (ssize_t
) Size
)
306 void raw_fd_ostream::close() {
307 assert (ShouldClose
);
310 if (::close(FD
) != 0)
315 uint64_t raw_fd_ostream::seek(uint64_t off
) {
317 pos
= ::lseek(FD
, off
, SEEK_SET
);
323 raw_ostream
&raw_fd_ostream::changeColor(enum Colors colors
, bool bold
,
325 if (sys::Process::ColorNeedsFlush())
327 const char *colorcode
=
328 (colors
== SAVEDCOLOR
) ? sys::Process::OutputBold(bg
)
329 : sys::Process::OutputColor(colors
, bold
, bg
);
331 unsigned len
= strlen(colorcode
);
332 write(colorcode
, len
);
333 // don't account colors towards output characters
339 raw_ostream
&raw_fd_ostream::resetColor() {
340 if (sys::Process::ColorNeedsFlush())
342 const char *colorcode
= sys::Process::ResetColor();
344 unsigned len
= strlen(colorcode
);
345 write(colorcode
, len
);
346 // don't account colors towards output characters
352 //===----------------------------------------------------------------------===//
353 // raw_stdout/err_ostream
354 //===----------------------------------------------------------------------===//
356 raw_stdout_ostream::raw_stdout_ostream():raw_fd_ostream(STDOUT_FILENO
, false) {}
357 raw_stderr_ostream::raw_stderr_ostream():raw_fd_ostream(STDERR_FILENO
, false,
360 // An out of line virtual method to provide a home for the class vtable.
361 void raw_stdout_ostream::handle() {}
362 void raw_stderr_ostream::handle() {}
364 /// outs() - This returns a reference to a raw_ostream for standard output.
365 /// Use it like: outs() << "foo" << "bar";
366 raw_ostream
&llvm::outs() {
367 static raw_stdout_ostream S
;
371 /// errs() - This returns a reference to a raw_ostream for standard error.
372 /// Use it like: errs() << "foo" << "bar";
373 raw_ostream
&llvm::errs() {
374 static raw_stderr_ostream S
;
378 //===----------------------------------------------------------------------===//
380 //===----------------------------------------------------------------------===//
382 raw_os_ostream::~raw_os_ostream() {
386 void raw_os_ostream::write_impl(const char *Ptr
, unsigned Size
) {
390 uint64_t raw_os_ostream::current_pos() { return OS
.tellp(); }
392 uint64_t raw_os_ostream::tell() {
393 return (uint64_t)OS
.tellp() + GetNumBytesInBuffer();
396 //===----------------------------------------------------------------------===//
397 // raw_string_ostream
398 //===----------------------------------------------------------------------===//
400 raw_string_ostream::~raw_string_ostream() {
404 void raw_string_ostream::write_impl(const char *Ptr
, unsigned Size
) {
405 OS
.append(Ptr
, Size
);
408 //===----------------------------------------------------------------------===//
409 // raw_svector_ostream
410 //===----------------------------------------------------------------------===//
412 raw_svector_ostream::~raw_svector_ostream() {
416 void raw_svector_ostream::write_impl(const char *Ptr
, unsigned Size
) {
417 OS
.append(Ptr
, Ptr
+ Size
);
420 uint64_t raw_svector_ostream::current_pos() { return OS
.size(); }
422 uint64_t raw_svector_ostream::tell() {
423 return OS
.size() + GetNumBytesInBuffer();