LLVM API Documentation
00001 //===--- raw_ostream.cpp - Implement the raw_ostream classes --------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This implements support for bulk buffered stream output. 00011 // 00012 //===----------------------------------------------------------------------===// 00013 00014 #include "llvm/Support/raw_ostream.h" 00015 #include "llvm/Support/Format.h" 00016 #include "llvm/System/Program.h" 00017 #include "llvm/System/Process.h" 00018 #include "llvm/ADT/SmallVector.h" 00019 #include "llvm/Config/config.h" 00020 #include "llvm/Support/Compiler.h" 00021 #include "llvm/Support/ErrorHandling.h" 00022 #include <ostream> 00023 #include <sys/stat.h> 00024 #include <sys/types.h> 00025 00026 #if defined(HAVE_UNISTD_H) 00027 # include <unistd.h> 00028 #endif 00029 #if defined(HAVE_FCNTL_H) 00030 # include <fcntl.h> 00031 #endif 00032 00033 #if defined(_MSC_VER) 00034 #include <io.h> 00035 #include <fcntl.h> 00036 #ifndef STDIN_FILENO 00037 # define STDIN_FILENO 0 00038 #endif 00039 #ifndef STDOUT_FILENO 00040 # define STDOUT_FILENO 1 00041 #endif 00042 #ifndef STDERR_FILENO 00043 # define STDERR_FILENO 2 00044 #endif 00045 #endif 00046 00047 using namespace llvm; 00048 00049 raw_ostream::~raw_ostream() { 00050 // raw_ostream's subclasses should take care to flush the buffer 00051 // in their destructors. 00052 assert(OutBufCur == OutBufStart && 00053 "raw_ostream destructor called with non-empty buffer!"); 00054 00055 if (BufferMode == InternalBuffer) 00056 delete [] OutBufStart; 00057 00058 // If there are any pending errors, report them now. Clients wishing 00059 // to avoid llvm_report_error calls should check for errors with 00060 // has_error() and clear the error flag with clear_error() before 00061 // destructing raw_ostream objects which may have errors. 00062 if (Error) 00063 llvm_report_error("IO failure on output stream."); 00064 } 00065 00066 // An out of line virtual method to provide a home for the class vtable. 00067 void raw_ostream::handle() {} 00068 00069 size_t raw_ostream::preferred_buffer_size() { 00070 // BUFSIZ is intended to be a reasonable default. 00071 return BUFSIZ; 00072 } 00073 00074 void raw_ostream::SetBuffered() { 00075 // Ask the subclass to determine an appropriate buffer size. 00076 if (size_t Size = preferred_buffer_size()) 00077 SetBufferSize(Size); 00078 else 00079 // It may return 0, meaning this stream should be unbuffered. 00080 SetUnbuffered(); 00081 } 00082 00083 void raw_ostream::SetBufferAndMode(char *BufferStart, size_t Size, 00084 BufferKind Mode) { 00085 assert(((Mode == Unbuffered && BufferStart == 0 && Size == 0) || 00086 (Mode != Unbuffered && BufferStart && Size >= 64)) && 00087 "stream must be unbuffered, or have >= 64 bytes of buffer"); 00088 // Make sure the current buffer is free of content (we can't flush here; the 00089 // child buffer management logic will be in write_impl). 00090 assert(GetNumBytesInBuffer() == 0 && "Current buffer is non-empty!"); 00091 00092 if (BufferMode == InternalBuffer) 00093 delete [] OutBufStart; 00094 OutBufStart = BufferStart; 00095 OutBufEnd = OutBufStart+Size; 00096 OutBufCur = OutBufStart; 00097 BufferMode = Mode; 00098 00099 assert(OutBufStart <= OutBufEnd && "Invalid size!"); 00100 } 00101 00102 raw_ostream &raw_ostream::operator<<(unsigned long N) { 00103 // Zero is a special case. 00104 if (N == 0) 00105 return *this << '0'; 00106 00107 char NumberBuffer[20]; 00108 char *EndPtr = NumberBuffer+sizeof(NumberBuffer); 00109 char *CurPtr = EndPtr; 00110 00111 while (N) { 00112 *--CurPtr = '0' + char(N % 10); 00113 N /= 10; 00114 } 00115 return write(CurPtr, EndPtr-CurPtr); 00116 } 00117 00118 raw_ostream &raw_ostream::operator<<(long N) { 00119 if (N < 0) { 00120 *this << '-'; 00121 N = -N; 00122 } 00123 00124 return this->operator<<(static_cast<unsigned long>(N)); 00125 } 00126 00127 raw_ostream &raw_ostream::operator<<(unsigned long long N) { 00128 // Output using 32-bit div/mod when possible. 00129 if (N == static_cast<unsigned long>(N)) 00130 return this->operator<<(static_cast<unsigned long>(N)); 00131 00132 char NumberBuffer[20]; 00133 char *EndPtr = NumberBuffer+sizeof(NumberBuffer); 00134 char *CurPtr = EndPtr; 00135 00136 while (N) { 00137 *--CurPtr = '0' + char(N % 10); 00138 N /= 10; 00139 } 00140 return write(CurPtr, EndPtr-CurPtr); 00141 } 00142 00143 raw_ostream &raw_ostream::operator<<(long long N) { 00144 if (N < 0) { 00145 *this << '-'; 00146 N = -N; 00147 } 00148 00149 return this->operator<<(static_cast<unsigned long long>(N)); 00150 } 00151 00152 raw_ostream &raw_ostream::write_hex(unsigned long long N) { 00153 // Zero is a special case. 00154 if (N == 0) 00155 return *this << '0'; 00156 00157 char NumberBuffer[20]; 00158 char *EndPtr = NumberBuffer+sizeof(NumberBuffer); 00159 char *CurPtr = EndPtr; 00160 00161 while (N) { 00162 uintptr_t x = N % 16; 00163 *--CurPtr = (x < 10 ? '0' + x : 'a' + x - 10); 00164 N /= 16; 00165 } 00166 00167 return write(CurPtr, EndPtr-CurPtr); 00168 } 00169 00170 raw_ostream &raw_ostream::operator<<(const void *P) { 00171 *this << '0' << 'x'; 00172 00173 return write_hex((uintptr_t) P); 00174 } 00175 00176 void raw_ostream::flush_nonempty() { 00177 assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty."); 00178 size_t Length = OutBufCur - OutBufStart; 00179 OutBufCur = OutBufStart; 00180 write_impl(OutBufStart, Length); 00181 } 00182 00183 raw_ostream &raw_ostream::write(unsigned char C) { 00184 // Group exceptional cases into a single branch. 00185 if (BUILTIN_EXPECT(OutBufCur >= OutBufEnd, false)) { 00186 if (BUILTIN_EXPECT(!OutBufStart, false)) { 00187 if (BufferMode == Unbuffered) { 00188 write_impl(reinterpret_cast<char*>(&C), 1); 00189 return *this; 00190 } 00191 // Set up a buffer and start over. 00192 SetBuffered(); 00193 return write(C); 00194 } 00195 00196 flush_nonempty(); 00197 } 00198 00199 *OutBufCur++ = C; 00200 return *this; 00201 } 00202 00203 raw_ostream &raw_ostream::write(const char *Ptr, size_t Size) { 00204 // Group exceptional cases into a single branch. 00205 if (BUILTIN_EXPECT(OutBufCur+Size > OutBufEnd, false)) { 00206 if (BUILTIN_EXPECT(!OutBufStart, false)) { 00207 if (BufferMode == Unbuffered) { 00208 write_impl(Ptr, Size); 00209 return *this; 00210 } 00211 // Set up a buffer and start over. 00212 SetBuffered(); 00213 return write(Ptr, Size); 00214 } 00215 00216 // Write out the data in buffer-sized blocks until the remainder 00217 // fits within the buffer. 00218 do { 00219 size_t NumBytes = OutBufEnd - OutBufCur; 00220 copy_to_buffer(Ptr, NumBytes); 00221 flush_nonempty(); 00222 Ptr += NumBytes; 00223 Size -= NumBytes; 00224 } while (OutBufCur+Size > OutBufEnd); 00225 } 00226 00227 copy_to_buffer(Ptr, Size); 00228 00229 return *this; 00230 } 00231 00232 void raw_ostream::copy_to_buffer(const char *Ptr, size_t Size) { 00233 assert(Size <= size_t(OutBufEnd - OutBufCur) && "Buffer overrun!"); 00234 00235 // Handle short strings specially, memcpy isn't very good at very short 00236 // strings. 00237 switch (Size) { 00238 case 4: OutBufCur[3] = Ptr[3]; // FALL THROUGH 00239 case 3: OutBufCur[2] = Ptr[2]; // FALL THROUGH 00240 case 2: OutBufCur[1] = Ptr[1]; // FALL THROUGH 00241 case 1: OutBufCur[0] = Ptr[0]; // FALL THROUGH 00242 case 0: break; 00243 default: 00244 memcpy(OutBufCur, Ptr, Size); 00245 break; 00246 } 00247 00248 OutBufCur += Size; 00249 } 00250 00251 // Formatted output. 00252 raw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) { 00253 // If we have more than a few bytes left in our output buffer, try 00254 // formatting directly onto its end. 00255 size_t NextBufferSize = 127; 00256 size_t BufferBytesLeft = OutBufEnd - OutBufCur; 00257 if (BufferBytesLeft > 3) { 00258 size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft); 00259 00260 // Common case is that we have plenty of space. 00261 if (BytesUsed <= BufferBytesLeft) { 00262 OutBufCur += BytesUsed; 00263 return *this; 00264 } 00265 00266 // Otherwise, we overflowed and the return value tells us the size to try 00267 // again with. 00268 NextBufferSize = BytesUsed; 00269 } 00270 00271 // If we got here, we didn't have enough space in the output buffer for the 00272 // string. Try printing into a SmallVector that is resized to have enough 00273 // space. Iterate until we win. 00274 SmallVector<char, 128> V; 00275 00276 while (1) { 00277 V.resize(NextBufferSize); 00278 00279 // Try formatting into the SmallVector. 00280 size_t BytesUsed = Fmt.print(V.data(), NextBufferSize); 00281 00282 // If BytesUsed fit into the vector, we win. 00283 if (BytesUsed <= NextBufferSize) 00284 return write(V.data(), BytesUsed); 00285 00286 // Otherwise, try again with a new size. 00287 assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?"); 00288 NextBufferSize = BytesUsed; 00289 } 00290 } 00291 00292 //===----------------------------------------------------------------------===// 00293 // Formatted Output 00294 //===----------------------------------------------------------------------===// 00295 00296 // Out of line virtual method. 00297 void format_object_base::home() { 00298 } 00299 00300 //===----------------------------------------------------------------------===// 00301 // raw_fd_ostream 00302 //===----------------------------------------------------------------------===// 00303 00304 /// raw_fd_ostream - Open the specified file for writing. If an error 00305 /// occurs, information about the error is put into ErrorInfo, and the 00306 /// stream should be immediately destroyed; the string will be empty 00307 /// if no error occurred. 00308 raw_fd_ostream::raw_fd_ostream(const char *Filename, bool Binary, bool Force, 00309 std::string &ErrorInfo) : pos(0) { 00310 ErrorInfo.clear(); 00311 00312 // Handle "-" as stdout. 00313 if (Filename[0] == '-' && Filename[1] == 0) { 00314 FD = STDOUT_FILENO; 00315 // If user requested binary then put stdout into binary mode if 00316 // possible. 00317 if (Binary) 00318 sys::Program::ChangeStdoutToBinary(); 00319 ShouldClose = false; 00320 return; 00321 } 00322 00323 int Flags = O_WRONLY|O_CREAT|O_TRUNC; 00324 #ifdef O_BINARY 00325 if (Binary) 00326 Flags |= O_BINARY; 00327 #endif 00328 if (!Force) 00329 Flags |= O_EXCL; 00330 FD = open(Filename, Flags, 0664); 00331 if (FD < 0) { 00332 ErrorInfo = "Error opening output file '" + std::string(Filename) + "'"; 00333 ShouldClose = false; 00334 } else { 00335 ShouldClose = true; 00336 } 00337 } 00338 00339 raw_fd_ostream::~raw_fd_ostream() { 00340 if (FD >= 0) { 00341 flush(); 00342 if (ShouldClose) 00343 if (::close(FD) != 0) 00344 error_detected(); 00345 } 00346 } 00347 00348 void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) { 00349 assert (FD >= 0 && "File already closed."); 00350 pos += Size; 00351 if (::write(FD, Ptr, Size) != (ssize_t) Size) 00352 error_detected(); 00353 } 00354 00355 void raw_fd_ostream::close() { 00356 assert (ShouldClose); 00357 ShouldClose = false; 00358 flush(); 00359 if (::close(FD) != 0) 00360 error_detected(); 00361 FD = -1; 00362 } 00363 00364 uint64_t raw_fd_ostream::seek(uint64_t off) { 00365 flush(); 00366 pos = ::lseek(FD, off, SEEK_SET); 00367 if (pos != off) 00368 error_detected(); 00369 return pos; 00370 } 00371 00372 size_t raw_fd_ostream::preferred_buffer_size() { 00373 #if !defined(_MSC_VER) && !defined(__MINGW32__) // Windows has no st_blksize. 00374 assert(FD >= 0 && "File not yet open!"); 00375 struct stat statbuf; 00376 if (fstat(FD, &statbuf) == 0) { 00377 // If this is a terminal, don't use buffering. Line buffering 00378 // would be a more traditional thing to do, but it's not worth 00379 // the complexity. 00380 if (S_ISCHR(statbuf.st_mode) && isatty(FD)) 00381 return 0; 00382 // Return the preferred block size. 00383 return statbuf.st_blksize; 00384 } 00385 error_detected(); 00386 #endif 00387 return raw_ostream::preferred_buffer_size(); 00388 } 00389 00390 raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold, 00391 bool bg) { 00392 if (sys::Process::ColorNeedsFlush()) 00393 flush(); 00394 const char *colorcode = 00395 (colors == SAVEDCOLOR) ? sys::Process::OutputBold(bg) 00396 : sys::Process::OutputColor(colors, bold, bg); 00397 if (colorcode) { 00398 size_t len = strlen(colorcode); 00399 write(colorcode, len); 00400 // don't account colors towards output characters 00401 pos -= len; 00402 } 00403 return *this; 00404 } 00405 00406 raw_ostream &raw_fd_ostream::resetColor() { 00407 if (sys::Process::ColorNeedsFlush()) 00408 flush(); 00409 const char *colorcode = sys::Process::ResetColor(); 00410 if (colorcode) { 00411 size_t len = strlen(colorcode); 00412 write(colorcode, len); 00413 // don't account colors towards output characters 00414 pos -= len; 00415 } 00416 return *this; 00417 } 00418 00419 //===----------------------------------------------------------------------===// 00420 // raw_stdout/err_ostream 00421 //===----------------------------------------------------------------------===// 00422 00423 // Set buffer settings to model stdout and stderr behavior. 00424 // Set standard error to be unbuffered by default. 00425 raw_stdout_ostream::raw_stdout_ostream():raw_fd_ostream(STDOUT_FILENO, false) {} 00426 raw_stderr_ostream::raw_stderr_ostream():raw_fd_ostream(STDERR_FILENO, false, 00427 true) {} 00428 00429 // An out of line virtual method to provide a home for the class vtable. 00430 void raw_stdout_ostream::handle() {} 00431 void raw_stderr_ostream::handle() {} 00432 00433 /// outs() - This returns a reference to a raw_ostream for standard output. 00434 /// Use it like: outs() << "foo" << "bar"; 00435 raw_ostream &llvm::outs() { 00436 static raw_stdout_ostream S; 00437 return S; 00438 } 00439 00440 /// errs() - This returns a reference to a raw_ostream for standard error. 00441 /// Use it like: errs() << "foo" << "bar"; 00442 raw_ostream &llvm::errs() { 00443 static raw_stderr_ostream S; 00444 return S; 00445 } 00446 00447 /// nulls() - This returns a reference to a raw_ostream which discards output. 00448 raw_ostream &llvm::nulls() { 00449 static raw_null_ostream S; 00450 return S; 00451 } 00452 00453 //===----------------------------------------------------------------------===// 00454 // raw_os_ostream 00455 //===----------------------------------------------------------------------===// 00456 00457 raw_os_ostream::~raw_os_ostream() { 00458 flush(); 00459 } 00460 00461 void raw_os_ostream::write_impl(const char *Ptr, size_t Size) { 00462 OS.write(Ptr, Size); 00463 } 00464 00465 uint64_t raw_os_ostream::current_pos() { return OS.tellp(); } 00466 00467 //===----------------------------------------------------------------------===// 00468 // raw_string_ostream 00469 //===----------------------------------------------------------------------===// 00470 00471 raw_string_ostream::~raw_string_ostream() { 00472 flush(); 00473 } 00474 00475 void raw_string_ostream::write_impl(const char *Ptr, size_t Size) { 00476 OS.append(Ptr, Size); 00477 } 00478 00479 //===----------------------------------------------------------------------===// 00480 // raw_svector_ostream 00481 //===----------------------------------------------------------------------===// 00482 00483 // The raw_svector_ostream implementation uses the SmallVector itself as the 00484 // buffer for the raw_ostream. We guarantee that the raw_ostream buffer is 00485 // always pointing past the end of the vector, but within the vector 00486 // capacity. This allows raw_ostream to write directly into the correct place, 00487 // and we only need to set the vector size when the data is flushed. 00488 00489 raw_svector_ostream::raw_svector_ostream(SmallVectorImpl<char> &O) : OS(O) { 00490 // Set up the initial external buffer. We make sure that the buffer has at 00491 // least 128 bytes free; raw_ostream itself only requires 64, but we want to 00492 // make sure that we don't grow the buffer unnecessarily on destruction (when 00493 // the data is flushed). See the FIXME below. 00494 OS.reserve(OS.size() + 128); 00495 SetBuffer(OS.end(), OS.capacity() - OS.size()); 00496 } 00497 00498 raw_svector_ostream::~raw_svector_ostream() { 00499 // FIXME: Prevent resizing during this flush(). 00500 flush(); 00501 } 00502 00503 void raw_svector_ostream::write_impl(const char *Ptr, size_t Size) { 00504 assert(Ptr == OS.end() && OS.size() + Size <= OS.capacity() && 00505 "Invalid write_impl() call!"); 00506 00507 // We don't need to copy the bytes, just commit the bytes to the 00508 // SmallVector. 00509 OS.set_size(OS.size() + Size); 00510 00511 // Grow the vector if necessary. 00512 if (OS.capacity() - OS.size() < 64) 00513 OS.reserve(OS.capacity() * 2); 00514 00515 // Update the buffer position. 00516 SetBuffer(OS.end(), OS.capacity() - OS.size()); 00517 } 00518 00519 uint64_t raw_svector_ostream::current_pos() { return OS.size(); } 00520 00521 StringRef raw_svector_ostream::str() { 00522 flush(); 00523 return StringRef(OS.begin(), OS.size()); 00524 } 00525 00526 //===----------------------------------------------------------------------===// 00527 // raw_null_ostream 00528 //===----------------------------------------------------------------------===// 00529 00530 raw_null_ostream::~raw_null_ostream() { 00531 #ifndef NDEBUG 00532 // ~raw_ostream asserts that the buffer is empty. This isn't necessary 00533 // with raw_null_ostream, but it's better to have raw_null_ostream follow 00534 // the rules than to change the rules just for raw_null_ostream. 00535 flush(); 00536 #endif 00537 } 00538 00539 void raw_null_ostream::write_impl(const char *Ptr, size_t Size) { 00540 } 00541 00542 uint64_t raw_null_ostream::current_pos() { 00543 return 0; 00544 }