raw_ostream.cpp revision 207618
1//===--- raw_ostream.cpp - Implement the raw_ostream classes --------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This implements support for bulk buffered stream output. 11// 12//===----------------------------------------------------------------------===// 13 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 <cctype> 24#include <sys/stat.h> 25#include <sys/types.h> 26 27#if defined(HAVE_UNISTD_H) 28# include <unistd.h> 29#endif 30#if defined(HAVE_FCNTL_H) 31# include <fcntl.h> 32#endif 33 34#if defined(_MSC_VER) 35#include <io.h> 36#include <fcntl.h> 37#ifndef STDIN_FILENO 38# define STDIN_FILENO 0 39#endif 40#ifndef STDOUT_FILENO 41# define STDOUT_FILENO 1 42#endif 43#ifndef STDERR_FILENO 44# define STDERR_FILENO 2 45#endif 46#endif 47 48using namespace llvm; 49 50raw_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!"); 55 56 if (BufferMode == InternalBuffer) 57 delete [] OutBufStart; 58 59 // If there are any pending errors, report them now. Clients wishing 60 // to avoid report_fatal_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. 63 if (Error) 64 report_fatal_error("IO failure on output stream."); 65} 66 67// An out of line virtual method to provide a home for the class vtable. 68void raw_ostream::handle() {} 69 70size_t raw_ostream::preferred_buffer_size() const { 71 // BUFSIZ is intended to be a reasonable default. 72 return BUFSIZ; 73} 74 75void raw_ostream::SetBuffered() { 76 // Ask the subclass to determine an appropriate buffer size. 77 if (size_t Size = preferred_buffer_size()) 78 SetBufferSize(Size); 79 else 80 // It may return 0, meaning this stream should be unbuffered. 81 SetUnbuffered(); 82} 83 84void raw_ostream::SetBufferAndMode(char *BufferStart, size_t Size, 85 BufferKind Mode) { 86 assert(((Mode == Unbuffered && BufferStart == 0 && Size == 0) || 87 (Mode != Unbuffered && BufferStart && Size)) && 88 "stream must be unbuffered or have at least one byte"); 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!"); 92 93 if (BufferMode == InternalBuffer) 94 delete [] OutBufStart; 95 OutBufStart = BufferStart; 96 OutBufEnd = OutBufStart+Size; 97 OutBufCur = OutBufStart; 98 BufferMode = Mode; 99 100 assert(OutBufStart <= OutBufEnd && "Invalid size!"); 101} 102 103raw_ostream &raw_ostream::operator<<(unsigned long N) { 104 // Zero is a special case. 105 if (N == 0) 106 return *this << '0'; 107 108 char NumberBuffer[20]; 109 char *EndPtr = NumberBuffer+sizeof(NumberBuffer); 110 char *CurPtr = EndPtr; 111 112 while (N) { 113 *--CurPtr = '0' + char(N % 10); 114 N /= 10; 115 } 116 return write(CurPtr, EndPtr-CurPtr); 117} 118 119raw_ostream &raw_ostream::operator<<(long N) { 120 if (N < 0) { 121 *this << '-'; 122 N = -N; 123 } 124 125 return this->operator<<(static_cast<unsigned long>(N)); 126} 127 128raw_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)); 132 133 char NumberBuffer[20]; 134 char *EndPtr = NumberBuffer+sizeof(NumberBuffer); 135 char *CurPtr = EndPtr; 136 137 while (N) { 138 *--CurPtr = '0' + char(N % 10); 139 N /= 10; 140 } 141 return write(CurPtr, EndPtr-CurPtr); 142} 143 144raw_ostream &raw_ostream::operator<<(long long N) { 145 if (N < 0) { 146 *this << '-'; 147 N = -N; 148 } 149 150 return this->operator<<(static_cast<unsigned long long>(N)); 151} 152 153raw_ostream &raw_ostream::write_hex(unsigned long long N) { 154 // Zero is a special case. 155 if (N == 0) 156 return *this << '0'; 157 158 char NumberBuffer[20]; 159 char *EndPtr = NumberBuffer+sizeof(NumberBuffer); 160 char *CurPtr = EndPtr; 161 162 while (N) { 163 uintptr_t x = N % 16; 164 *--CurPtr = (x < 10 ? '0' + x : 'a' + x - 10); 165 N /= 16; 166 } 167 168 return write(CurPtr, EndPtr-CurPtr); 169} 170 171raw_ostream &raw_ostream::write_escaped(StringRef Str) { 172 for (unsigned i = 0, e = Str.size(); i != e; ++i) { 173 unsigned char c = Str[i]; 174 175 switch (c) { 176 case '\\': 177 *this << '\\' << '\\'; 178 break; 179 case '\t': 180 *this << '\\' << 't'; 181 break; 182 case '\n': 183 *this << '\\' << 'n'; 184 break; 185 case '"': 186 *this << '\\' << '"'; 187 break; 188 default: 189 if (std::isprint(c)) { 190 *this << c; 191 break; 192 } 193 194 // Always expand to a 3-character octal escape. 195 *this << '\\'; 196 *this << char('0' + ((c >> 6) & 7)); 197 *this << char('0' + ((c >> 3) & 7)); 198 *this << char('0' + ((c >> 0) & 7)); 199 } 200 } 201 202 return *this; 203} 204 205raw_ostream &raw_ostream::operator<<(const void *P) { 206 *this << '0' << 'x'; 207 208 return write_hex((uintptr_t) P); 209} 210 211raw_ostream &raw_ostream::operator<<(double N) { 212 return this->operator<<(format("%e", N)); 213} 214 215 216 217void raw_ostream::flush_nonempty() { 218 assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty."); 219 size_t Length = OutBufCur - OutBufStart; 220 OutBufCur = OutBufStart; 221 write_impl(OutBufStart, Length); 222} 223 224raw_ostream &raw_ostream::write(unsigned char C) { 225 // Group exceptional cases into a single branch. 226 if (BUILTIN_EXPECT(OutBufCur >= OutBufEnd, false)) { 227 if (BUILTIN_EXPECT(!OutBufStart, false)) { 228 if (BufferMode == Unbuffered) { 229 write_impl(reinterpret_cast<char*>(&C), 1); 230 return *this; 231 } 232 // Set up a buffer and start over. 233 SetBuffered(); 234 return write(C); 235 } 236 237 flush_nonempty(); 238 } 239 240 *OutBufCur++ = C; 241 return *this; 242} 243 244raw_ostream &raw_ostream::write(const char *Ptr, size_t Size) { 245 // Group exceptional cases into a single branch. 246 if (BUILTIN_EXPECT(OutBufCur+Size > OutBufEnd, false)) { 247 if (BUILTIN_EXPECT(!OutBufStart, false)) { 248 if (BufferMode == Unbuffered) { 249 write_impl(Ptr, Size); 250 return *this; 251 } 252 // Set up a buffer and start over. 253 SetBuffered(); 254 return write(Ptr, Size); 255 } 256 257 // Write out the data in buffer-sized blocks until the remainder 258 // fits within the buffer. 259 do { 260 size_t NumBytes = OutBufEnd - OutBufCur; 261 copy_to_buffer(Ptr, NumBytes); 262 flush_nonempty(); 263 Ptr += NumBytes; 264 Size -= NumBytes; 265 } while (OutBufCur+Size > OutBufEnd); 266 } 267 268 copy_to_buffer(Ptr, Size); 269 270 return *this; 271} 272 273void raw_ostream::copy_to_buffer(const char *Ptr, size_t Size) { 274 assert(Size <= size_t(OutBufEnd - OutBufCur) && "Buffer overrun!"); 275 276 // Handle short strings specially, memcpy isn't very good at very short 277 // strings. 278 switch (Size) { 279 case 4: OutBufCur[3] = Ptr[3]; // FALL THROUGH 280 case 3: OutBufCur[2] = Ptr[2]; // FALL THROUGH 281 case 2: OutBufCur[1] = Ptr[1]; // FALL THROUGH 282 case 1: OutBufCur[0] = Ptr[0]; // FALL THROUGH 283 case 0: break; 284 default: 285 memcpy(OutBufCur, Ptr, Size); 286 break; 287 } 288 289 OutBufCur += Size; 290} 291 292// Formatted output. 293raw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) { 294 // If we have more than a few bytes left in our output buffer, try 295 // formatting directly onto its end. 296 size_t NextBufferSize = 127; 297 size_t BufferBytesLeft = OutBufEnd - OutBufCur; 298 if (BufferBytesLeft > 3) { 299 size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft); 300 301 // Common case is that we have plenty of space. 302 if (BytesUsed <= BufferBytesLeft) { 303 OutBufCur += BytesUsed; 304 return *this; 305 } 306 307 // Otherwise, we overflowed and the return value tells us the size to try 308 // again with. 309 NextBufferSize = BytesUsed; 310 } 311 312 // If we got here, we didn't have enough space in the output buffer for the 313 // string. Try printing into a SmallVector that is resized to have enough 314 // space. Iterate until we win. 315 SmallVector<char, 128> V; 316 317 while (1) { 318 V.resize(NextBufferSize); 319 320 // Try formatting into the SmallVector. 321 size_t BytesUsed = Fmt.print(V.data(), NextBufferSize); 322 323 // If BytesUsed fit into the vector, we win. 324 if (BytesUsed <= NextBufferSize) 325 return write(V.data(), BytesUsed); 326 327 // Otherwise, try again with a new size. 328 assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?"); 329 NextBufferSize = BytesUsed; 330 } 331} 332 333/// indent - Insert 'NumSpaces' spaces. 334raw_ostream &raw_ostream::indent(unsigned NumSpaces) { 335 static const char Spaces[] = " " 336 " " 337 " "; 338 339 // Usually the indentation is small, handle it with a fastpath. 340 if (NumSpaces < array_lengthof(Spaces)) 341 return write(Spaces, NumSpaces); 342 343 while (NumSpaces) { 344 unsigned NumToWrite = std::min(NumSpaces, 345 (unsigned)array_lengthof(Spaces)-1); 346 write(Spaces, NumToWrite); 347 NumSpaces -= NumToWrite; 348 } 349 return *this; 350} 351 352 353//===----------------------------------------------------------------------===// 354// Formatted Output 355//===----------------------------------------------------------------------===// 356 357// Out of line virtual method. 358void format_object_base::home() { 359} 360 361//===----------------------------------------------------------------------===// 362// raw_fd_ostream 363//===----------------------------------------------------------------------===// 364 365/// raw_fd_ostream - Open the specified file for writing. If an error 366/// occurs, information about the error is put into ErrorInfo, and the 367/// stream should be immediately destroyed; the string will be empty 368/// if no error occurred. 369raw_fd_ostream::raw_fd_ostream(const char *Filename, std::string &ErrorInfo, 370 unsigned Flags) : pos(0) { 371 assert(Filename != 0 && "Filename is null"); 372 // Verify that we don't have both "append" and "excl". 373 assert((!(Flags & F_Excl) || !(Flags & F_Append)) && 374 "Cannot specify both 'excl' and 'append' file creation flags!"); 375 376 ErrorInfo.clear(); 377 378 // Handle "-" as stdout. 379 if (Filename[0] == '-' && Filename[1] == 0) { 380 FD = STDOUT_FILENO; 381 // If user requested binary then put stdout into binary mode if 382 // possible. 383 if (Flags & F_Binary) 384 sys::Program::ChangeStdoutToBinary(); 385 ShouldClose = false; 386 return; 387 } 388 389 int OpenFlags = O_WRONLY|O_CREAT; 390#ifdef O_BINARY 391 if (Flags & F_Binary) 392 OpenFlags |= O_BINARY; 393#endif 394 395 if (Flags & F_Append) 396 OpenFlags |= O_APPEND; 397 else 398 OpenFlags |= O_TRUNC; 399 if (Flags & F_Excl) 400 OpenFlags |= O_EXCL; 401 402 FD = open(Filename, OpenFlags, 0664); 403 if (FD < 0) { 404 ErrorInfo = "Error opening output file '" + std::string(Filename) + "'"; 405 ShouldClose = false; 406 } else { 407 ShouldClose = true; 408 } 409} 410 411raw_fd_ostream::~raw_fd_ostream() { 412 if (FD < 0) return; 413 flush(); 414 if (ShouldClose) 415 if (::close(FD) != 0) 416 error_detected(); 417} 418 419 420void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) { 421 assert(FD >= 0 && "File already closed."); 422 pos += Size; 423 if (::write(FD, Ptr, Size) != (ssize_t) Size) 424 error_detected(); 425} 426 427void raw_fd_ostream::close() { 428 assert(ShouldClose); 429 ShouldClose = false; 430 flush(); 431 if (::close(FD) != 0) 432 error_detected(); 433 FD = -1; 434} 435 436uint64_t raw_fd_ostream::seek(uint64_t off) { 437 flush(); 438 pos = ::lseek(FD, off, SEEK_SET); 439 if (pos != off) 440 error_detected(); 441 return pos; 442} 443 444size_t raw_fd_ostream::preferred_buffer_size() const { 445#if !defined(_MSC_VER) && !defined(__MINGW32__) && !defined(_MINIX) 446 // Windows and Minix have no st_blksize. 447 assert(FD >= 0 && "File not yet open!"); 448 struct stat statbuf; 449 if (fstat(FD, &statbuf) != 0) 450 return 0; 451 452 // If this is a terminal, don't use buffering. Line buffering 453 // would be a more traditional thing to do, but it's not worth 454 // the complexity. 455 if (S_ISCHR(statbuf.st_mode) && isatty(FD)) 456 return 0; 457 // Return the preferred block size. 458 return statbuf.st_blksize; 459#endif 460 return raw_ostream::preferred_buffer_size(); 461} 462 463raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold, 464 bool bg) { 465 if (sys::Process::ColorNeedsFlush()) 466 flush(); 467 const char *colorcode = 468 (colors == SAVEDCOLOR) ? sys::Process::OutputBold(bg) 469 : sys::Process::OutputColor(colors, bold, bg); 470 if (colorcode) { 471 size_t len = strlen(colorcode); 472 write(colorcode, len); 473 // don't account colors towards output characters 474 pos -= len; 475 } 476 return *this; 477} 478 479raw_ostream &raw_fd_ostream::resetColor() { 480 if (sys::Process::ColorNeedsFlush()) 481 flush(); 482 const char *colorcode = sys::Process::ResetColor(); 483 if (colorcode) { 484 size_t len = strlen(colorcode); 485 write(colorcode, len); 486 // don't account colors towards output characters 487 pos -= len; 488 } 489 return *this; 490} 491 492bool raw_fd_ostream::is_displayed() const { 493 return sys::Process::FileDescriptorIsDisplayed(FD); 494} 495 496//===----------------------------------------------------------------------===// 497// raw_stdout/err_ostream 498//===----------------------------------------------------------------------===// 499 500// Set buffer settings to model stdout and stderr behavior. 501// Set standard error to be unbuffered by default. 502raw_stdout_ostream::raw_stdout_ostream():raw_fd_ostream(STDOUT_FILENO, false) {} 503raw_stderr_ostream::raw_stderr_ostream():raw_fd_ostream(STDERR_FILENO, false, 504 true) {} 505 506// An out of line virtual method to provide a home for the class vtable. 507void raw_stdout_ostream::handle() {} 508void raw_stderr_ostream::handle() {} 509 510/// outs() - This returns a reference to a raw_ostream for standard output. 511/// Use it like: outs() << "foo" << "bar"; 512raw_ostream &llvm::outs() { 513 static raw_stdout_ostream S; 514 return S; 515} 516 517/// errs() - This returns a reference to a raw_ostream for standard error. 518/// Use it like: errs() << "foo" << "bar"; 519raw_ostream &llvm::errs() { 520 static raw_stderr_ostream S; 521 return S; 522} 523 524/// nulls() - This returns a reference to a raw_ostream which discards output. 525raw_ostream &llvm::nulls() { 526 static raw_null_ostream S; 527 return S; 528} 529 530 531//===----------------------------------------------------------------------===// 532// raw_string_ostream 533//===----------------------------------------------------------------------===// 534 535raw_string_ostream::~raw_string_ostream() { 536 flush(); 537} 538 539void raw_string_ostream::write_impl(const char *Ptr, size_t Size) { 540 OS.append(Ptr, Size); 541} 542 543//===----------------------------------------------------------------------===// 544// raw_svector_ostream 545//===----------------------------------------------------------------------===// 546 547// The raw_svector_ostream implementation uses the SmallVector itself as the 548// buffer for the raw_ostream. We guarantee that the raw_ostream buffer is 549// always pointing past the end of the vector, but within the vector 550// capacity. This allows raw_ostream to write directly into the correct place, 551// and we only need to set the vector size when the data is flushed. 552 553raw_svector_ostream::raw_svector_ostream(SmallVectorImpl<char> &O) : OS(O) { 554 // Set up the initial external buffer. We make sure that the buffer has at 555 // least 128 bytes free; raw_ostream itself only requires 64, but we want to 556 // make sure that we don't grow the buffer unnecessarily on destruction (when 557 // the data is flushed). See the FIXME below. 558 OS.reserve(OS.size() + 128); 559 SetBuffer(OS.end(), OS.capacity() - OS.size()); 560} 561 562raw_svector_ostream::~raw_svector_ostream() { 563 // FIXME: Prevent resizing during this flush(). 564 flush(); 565} 566 567/// resync - This is called when the SmallVector we're appending to is changed 568/// outside of the raw_svector_ostream's control. It is only safe to do this 569/// if the raw_svector_ostream has previously been flushed. 570void raw_svector_ostream::resync() { 571 assert(GetNumBytesInBuffer() == 0 && "Didn't flush before mutating vector"); 572 573 if (OS.capacity() - OS.size() < 64) 574 OS.reserve(OS.capacity() * 2); 575 SetBuffer(OS.end(), OS.capacity() - OS.size()); 576} 577 578void raw_svector_ostream::write_impl(const char *Ptr, size_t Size) { 579 // If we're writing bytes from the end of the buffer into the smallvector, we 580 // don't need to copy the bytes, just commit the bytes because they are 581 // already in the right place. 582 if (Ptr == OS.end()) { 583 assert(OS.size() + Size <= OS.capacity() && "Invalid write_impl() call!"); 584 OS.set_size(OS.size() + Size); 585 } else { 586 assert(GetNumBytesInBuffer() == 0 && 587 "Should be writing from buffer if some bytes in it"); 588 // Otherwise, do copy the bytes. 589 OS.append(Ptr, Ptr+Size); 590 } 591 592 // Grow the vector if necessary. 593 if (OS.capacity() - OS.size() < 64) 594 OS.reserve(OS.capacity() * 2); 595 596 // Update the buffer position. 597 SetBuffer(OS.end(), OS.capacity() - OS.size()); 598} 599 600uint64_t raw_svector_ostream::current_pos() const { 601 return OS.size(); 602} 603 604StringRef raw_svector_ostream::str() { 605 flush(); 606 return StringRef(OS.begin(), OS.size()); 607} 608 609//===----------------------------------------------------------------------===// 610// raw_null_ostream 611//===----------------------------------------------------------------------===// 612 613raw_null_ostream::~raw_null_ostream() { 614#ifndef NDEBUG 615 // ~raw_ostream asserts that the buffer is empty. This isn't necessary 616 // with raw_null_ostream, but it's better to have raw_null_ostream follow 617 // the rules than to change the rules just for raw_null_ostream. 618 flush(); 619#endif 620} 621 622void raw_null_ostream::write_impl(const char *Ptr, size_t Size) { 623} 624 625uint64_t raw_null_ostream::current_pos() const { 626 return 0; 627} 628