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/ADT/STLExtras.h" 16 #include "llvm/ADT/SmallVector.h" 17 #include "llvm/ADT/StringExtras.h" 18 #include "llvm/Config/config.h" 19 #include "llvm/Support/Compiler.h" 20 #include "llvm/Support/ErrorHandling.h" 21 #include "llvm/Support/FileSystem.h" 22 #include "llvm/Support/Format.h" 23 #include "llvm/Support/FormatVariadic.h" 24 #include "llvm/Support/MathExtras.h" 25 #include "llvm/Support/NativeFormatting.h" 26 #include "llvm/Support/Process.h" 27 #include "llvm/Support/Program.h" 28 #include <algorithm> 29 #include <cctype> 30 #include <cerrno> 31 #include <cstdio> 32 #include <iterator> 33 #include <sys/stat.h> 34 #include <system_error> 35 36 // <fcntl.h> may provide O_BINARY. 37 #if defined(HAVE_FCNTL_H) 38 # include <fcntl.h> 39 #endif 40 41 #if defined(HAVE_UNISTD_H) 42 # include <unistd.h> 43 #endif 44 45 #if defined(__CYGWIN__) 46 #include <io.h> 47 #endif 48 49 #if defined(_MSC_VER) 50 #include <io.h> 51 #ifndef STDIN_FILENO 52 # define STDIN_FILENO 0 53 #endif 54 #ifndef STDOUT_FILENO 55 # define STDOUT_FILENO 1 56 #endif 57 #ifndef STDERR_FILENO 58 # define STDERR_FILENO 2 59 #endif 60 #endif 61 62 #ifdef LLVM_ON_WIN32 63 #include "Windows/WindowsSupport.h" 64 #endif 65 66 using namespace llvm; 67 68 raw_ostream::~raw_ostream() { 69 // raw_ostream's subclasses should take care to flush the buffer 70 // in their destructors. 71 assert(OutBufCur == OutBufStart && 72 "raw_ostream destructor called with non-empty buffer!"); 73 74 if (BufferMode == InternalBuffer) 75 delete [] OutBufStart; 76 } 77 78 // An out of line virtual method to provide a home for the class vtable. 79 void raw_ostream::handle() {} 80 81 size_t raw_ostream::preferred_buffer_size() const { 82 // BUFSIZ is intended to be a reasonable default. 83 return BUFSIZ; 84 } 85 86 void raw_ostream::SetBuffered() { 87 // Ask the subclass to determine an appropriate buffer size. 88 if (size_t Size = preferred_buffer_size()) 89 SetBufferSize(Size); 90 else 91 // It may return 0, meaning this stream should be unbuffered. 92 SetUnbuffered(); 93 } 94 95 void raw_ostream::SetBufferAndMode(char *BufferStart, size_t Size, 96 BufferKind Mode) { 97 assert(((Mode == Unbuffered && !BufferStart && Size == 0) || 98 (Mode != Unbuffered && BufferStart && Size != 0)) && 99 "stream must be unbuffered or have at least one byte"); 100 // Make sure the current buffer is free of content (we can't flush here; the 101 // child buffer management logic will be in write_impl). 102 assert(GetNumBytesInBuffer() == 0 && "Current buffer is non-empty!"); 103 104 if (BufferMode == InternalBuffer) 105 delete [] OutBufStart; 106 OutBufStart = BufferStart; 107 OutBufEnd = OutBufStart+Size; 108 OutBufCur = OutBufStart; 109 BufferMode = Mode; 110 111 assert(OutBufStart <= OutBufEnd && "Invalid size!"); 112 } 113 114 raw_ostream &raw_ostream::operator<<(unsigned long N) { 115 write_integer(*this, static_cast<uint64_t>(N), 0, IntegerStyle::Integer); 116 return *this; 117 } 118 119 raw_ostream &raw_ostream::operator<<(long N) { 120 write_integer(*this, static_cast<int64_t>(N), 0, IntegerStyle::Integer); 121 return *this; 122 } 123 124 raw_ostream &raw_ostream::operator<<(unsigned long long N) { 125 write_integer(*this, static_cast<uint64_t>(N), 0, IntegerStyle::Integer); 126 return *this; 127 } 128 129 raw_ostream &raw_ostream::operator<<(long long N) { 130 write_integer(*this, static_cast<int64_t>(N), 0, IntegerStyle::Integer); 131 return *this; 132 } 133 134 raw_ostream &raw_ostream::write_hex(unsigned long long N) { 135 llvm::write_hex(*this, N, HexPrintStyle::Lower); 136 return *this; 137 } 138 139 raw_ostream &raw_ostream::write_uuid(const uuid_t UUID) { 140 for (int Idx = 0; Idx < 16; ++Idx) { 141 *this << format("%02" PRIX32, UUID[Idx]); 142 if (Idx == 3 || Idx == 5 || Idx == 7 || Idx == 9) 143 *this << "-"; 144 } 145 return *this; 146 } 147 148 149 raw_ostream &raw_ostream::write_escaped(StringRef Str, 150 bool UseHexEscapes) { 151 for (unsigned char c : Str) { 152 switch (c) { 153 case '\\': 154 *this << '\\' << '\\'; 155 break; 156 case '\t': 157 *this << '\\' << 't'; 158 break; 159 case '\n': 160 *this << '\\' << 'n'; 161 break; 162 case '"': 163 *this << '\\' << '"'; 164 break; 165 default: 166 if (std::isprint(c)) { 167 *this << c; 168 break; 169 } 170 171 // Write out the escaped representation. 172 if (UseHexEscapes) { 173 *this << '\\' << 'x'; 174 *this << hexdigit((c >> 4 & 0xF)); 175 *this << hexdigit((c >> 0) & 0xF); 176 } else { 177 // Always use a full 3-character octal escape. 178 *this << '\\'; 179 *this << char('0' + ((c >> 6) & 7)); 180 *this << char('0' + ((c >> 3) & 7)); 181 *this << char('0' + ((c >> 0) & 7)); 182 } 183 } 184 } 185 186 return *this; 187 } 188 189 raw_ostream &raw_ostream::operator<<(const void *P) { 190 llvm::write_hex(*this, (uintptr_t)P, HexPrintStyle::PrefixLower); 191 return *this; 192 } 193 194 raw_ostream &raw_ostream::operator<<(double N) { 195 llvm::write_double(*this, N, FloatStyle::Exponent); 196 return *this; 197 } 198 199 void raw_ostream::flush_nonempty() { 200 assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty."); 201 size_t Length = OutBufCur - OutBufStart; 202 OutBufCur = OutBufStart; 203 write_impl(OutBufStart, Length); 204 } 205 206 raw_ostream &raw_ostream::write(unsigned char C) { 207 // Group exceptional cases into a single branch. 208 if (LLVM_UNLIKELY(OutBufCur >= OutBufEnd)) { 209 if (LLVM_UNLIKELY(!OutBufStart)) { 210 if (BufferMode == Unbuffered) { 211 write_impl(reinterpret_cast<char*>(&C), 1); 212 return *this; 213 } 214 // Set up a buffer and start over. 215 SetBuffered(); 216 return write(C); 217 } 218 219 flush_nonempty(); 220 } 221 222 *OutBufCur++ = C; 223 return *this; 224 } 225 226 raw_ostream &raw_ostream::write(const char *Ptr, size_t Size) { 227 // Group exceptional cases into a single branch. 228 if (LLVM_UNLIKELY(size_t(OutBufEnd - OutBufCur) < Size)) { 229 if (LLVM_UNLIKELY(!OutBufStart)) { 230 if (BufferMode == Unbuffered) { 231 write_impl(Ptr, Size); 232 return *this; 233 } 234 // Set up a buffer and start over. 235 SetBuffered(); 236 return write(Ptr, Size); 237 } 238 239 size_t NumBytes = OutBufEnd - OutBufCur; 240 241 // If the buffer is empty at this point we have a string that is larger 242 // than the buffer. Directly write the chunk that is a multiple of the 243 // preferred buffer size and put the remainder in the buffer. 244 if (LLVM_UNLIKELY(OutBufCur == OutBufStart)) { 245 assert(NumBytes != 0 && "undefined behavior"); 246 size_t BytesToWrite = Size - (Size % NumBytes); 247 write_impl(Ptr, BytesToWrite); 248 size_t BytesRemaining = Size - BytesToWrite; 249 if (BytesRemaining > size_t(OutBufEnd - OutBufCur)) { 250 // Too much left over to copy into our buffer. 251 return write(Ptr + BytesToWrite, BytesRemaining); 252 } 253 copy_to_buffer(Ptr + BytesToWrite, BytesRemaining); 254 return *this; 255 } 256 257 // We don't have enough space in the buffer to fit the string in. Insert as 258 // much as possible, flush and start over with the remainder. 259 copy_to_buffer(Ptr, NumBytes); 260 flush_nonempty(); 261 return write(Ptr + NumBytes, Size - NumBytes); 262 } 263 264 copy_to_buffer(Ptr, Size); 265 266 return *this; 267 } 268 269 void raw_ostream::copy_to_buffer(const char *Ptr, size_t Size) { 270 assert(Size <= size_t(OutBufEnd - OutBufCur) && "Buffer overrun!"); 271 272 // Handle short strings specially, memcpy isn't very good at very short 273 // strings. 274 switch (Size) { 275 case 4: OutBufCur[3] = Ptr[3]; LLVM_FALLTHROUGH; 276 case 3: OutBufCur[2] = Ptr[2]; LLVM_FALLTHROUGH; 277 case 2: OutBufCur[1] = Ptr[1]; LLVM_FALLTHROUGH; 278 case 1: OutBufCur[0] = Ptr[0]; LLVM_FALLTHROUGH; 279 case 0: break; 280 default: 281 memcpy(OutBufCur, Ptr, Size); 282 break; 283 } 284 285 OutBufCur += Size; 286 } 287 288 // Formatted output. 289 raw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) { 290 // If we have more than a few bytes left in our output buffer, try 291 // formatting directly onto its end. 292 size_t NextBufferSize = 127; 293 size_t BufferBytesLeft = OutBufEnd - OutBufCur; 294 if (BufferBytesLeft > 3) { 295 size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft); 296 297 // Common case is that we have plenty of space. 298 if (BytesUsed <= BufferBytesLeft) { 299 OutBufCur += BytesUsed; 300 return *this; 301 } 302 303 // Otherwise, we overflowed and the return value tells us the size to try 304 // again with. 305 NextBufferSize = BytesUsed; 306 } 307 308 // If we got here, we didn't have enough space in the output buffer for the 309 // string. Try printing into a SmallVector that is resized to have enough 310 // space. Iterate until we win. 311 SmallVector<char, 128> V; 312 313 while (true) { 314 V.resize(NextBufferSize); 315 316 // Try formatting into the SmallVector. 317 size_t BytesUsed = Fmt.print(V.data(), NextBufferSize); 318 319 // If BytesUsed fit into the vector, we win. 320 if (BytesUsed <= NextBufferSize) 321 return write(V.data(), BytesUsed); 322 323 // Otherwise, try again with a new size. 324 assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?"); 325 NextBufferSize = BytesUsed; 326 } 327 } 328 329 raw_ostream &raw_ostream::operator<<(const formatv_object_base &Obj) { 330 SmallString<128> S; 331 Obj.format(*this); 332 return *this; 333 } 334 335 raw_ostream &raw_ostream::operator<<(const FormattedString &FS) { 336 if (FS.Str.size() >= FS.Width || FS.Justify == FormattedString::JustifyNone) { 337 this->operator<<(FS.Str); 338 return *this; 339 } 340 const size_t Difference = FS.Width - FS.Str.size(); 341 switch (FS.Justify) { 342 case FormattedString::JustifyLeft: 343 this->operator<<(FS.Str); 344 this->indent(Difference); 345 break; 346 case FormattedString::JustifyRight: 347 this->indent(Difference); 348 this->operator<<(FS.Str); 349 break; 350 case FormattedString::JustifyCenter: { 351 int PadAmount = Difference / 2; 352 this->indent(PadAmount); 353 this->operator<<(FS.Str); 354 this->indent(Difference - PadAmount); 355 break; 356 } 357 default: 358 llvm_unreachable("Bad Justification"); 359 } 360 return *this; 361 } 362 363 raw_ostream &raw_ostream::operator<<(const FormattedNumber &FN) { 364 if (FN.Hex) { 365 HexPrintStyle Style; 366 if (FN.Upper && FN.HexPrefix) 367 Style = HexPrintStyle::PrefixUpper; 368 else if (FN.Upper && !FN.HexPrefix) 369 Style = HexPrintStyle::Upper; 370 else if (!FN.Upper && FN.HexPrefix) 371 Style = HexPrintStyle::PrefixLower; 372 else 373 Style = HexPrintStyle::Lower; 374 llvm::write_hex(*this, FN.HexValue, Style, FN.Width); 375 } else { 376 llvm::SmallString<16> Buffer; 377 llvm::raw_svector_ostream Stream(Buffer); 378 llvm::write_integer(Stream, FN.DecValue, 0, IntegerStyle::Integer); 379 if (Buffer.size() < FN.Width) 380 indent(FN.Width - Buffer.size()); 381 (*this) << Buffer; 382 } 383 return *this; 384 } 385 386 raw_ostream &raw_ostream::operator<<(const FormattedBytes &FB) { 387 if (FB.Bytes.empty()) 388 return *this; 389 390 size_t LineIndex = 0; 391 auto Bytes = FB.Bytes; 392 const size_t Size = Bytes.size(); 393 HexPrintStyle HPS = FB.Upper ? HexPrintStyle::Upper : HexPrintStyle::Lower; 394 uint64_t OffsetWidth = 0; 395 if (FB.FirstByteOffset.hasValue()) { 396 // Figure out how many nibbles are needed to print the largest offset 397 // represented by this data set, so that we can align the offset field 398 // to the right width. 399 size_t Lines = Size / FB.NumPerLine; 400 uint64_t MaxOffset = *FB.FirstByteOffset + Lines * FB.NumPerLine; 401 unsigned Power = 0; 402 if (MaxOffset > 0) 403 Power = llvm::Log2_64_Ceil(MaxOffset); 404 OffsetWidth = std::max<uint64_t>(4, llvm::alignTo(Power, 4) / 4); 405 } 406 407 // The width of a block of data including all spaces for group separators. 408 unsigned NumByteGroups = 409 alignTo(FB.NumPerLine, FB.ByteGroupSize) / FB.ByteGroupSize; 410 unsigned BlockCharWidth = FB.NumPerLine * 2 + NumByteGroups - 1; 411 412 while (!Bytes.empty()) { 413 indent(FB.IndentLevel); 414 415 if (FB.FirstByteOffset.hasValue()) { 416 uint64_t Offset = FB.FirstByteOffset.getValue(); 417 llvm::write_hex(*this, Offset + LineIndex, HPS, OffsetWidth); 418 *this << ": "; 419 } 420 421 auto Line = Bytes.take_front(FB.NumPerLine); 422 423 size_t CharsPrinted = 0; 424 // Print the hex bytes for this line in groups 425 for (size_t I = 0; I < Line.size(); ++I, CharsPrinted += 2) { 426 if (I && (I % FB.ByteGroupSize) == 0) { 427 ++CharsPrinted; 428 *this << " "; 429 } 430 llvm::write_hex(*this, Line[I], HPS, 2); 431 } 432 433 if (FB.ASCII) { 434 // Print any spaces needed for any bytes that we didn't print on this 435 // line so that the ASCII bytes are correctly aligned. 436 assert(BlockCharWidth >= CharsPrinted); 437 indent(BlockCharWidth - CharsPrinted + 2); 438 *this << "|"; 439 440 // Print the ASCII char values for each byte on this line 441 for (uint8_t Byte : Line) { 442 if (isprint(Byte)) 443 *this << static_cast<char>(Byte); 444 else 445 *this << '.'; 446 } 447 *this << '|'; 448 } 449 450 Bytes = Bytes.drop_front(Line.size()); 451 LineIndex += Line.size(); 452 if (LineIndex < Size) 453 *this << '\n'; 454 } 455 return *this; 456 } 457 458 /// indent - Insert 'NumSpaces' spaces. 459 raw_ostream &raw_ostream::indent(unsigned NumSpaces) { 460 static const char Spaces[] = " " 461 " " 462 " "; 463 464 // Usually the indentation is small, handle it with a fastpath. 465 if (NumSpaces < array_lengthof(Spaces)) 466 return write(Spaces, NumSpaces); 467 468 while (NumSpaces) { 469 unsigned NumToWrite = std::min(NumSpaces, 470 (unsigned)array_lengthof(Spaces)-1); 471 write(Spaces, NumToWrite); 472 NumSpaces -= NumToWrite; 473 } 474 return *this; 475 } 476 477 //===----------------------------------------------------------------------===// 478 // Formatted Output 479 //===----------------------------------------------------------------------===// 480 481 // Out of line virtual method. 482 void format_object_base::home() { 483 } 484 485 //===----------------------------------------------------------------------===// 486 // raw_fd_ostream 487 //===----------------------------------------------------------------------===// 488 489 static int getFD(StringRef Filename, std::error_code &EC, 490 sys::fs::OpenFlags Flags) { 491 // Handle "-" as stdout. Note that when we do this, we consider ourself 492 // the owner of stdout and may set the "binary" flag globally based on Flags. 493 if (Filename == "-") { 494 EC = std::error_code(); 495 // If user requested binary then put stdout into binary mode if 496 // possible. 497 if (!(Flags & sys::fs::F_Text)) 498 sys::ChangeStdoutToBinary(); 499 return STDOUT_FILENO; 500 } 501 502 int FD; 503 EC = sys::fs::openFileForWrite(Filename, FD, Flags); 504 if (EC) 505 return -1; 506 507 return FD; 508 } 509 510 raw_fd_ostream::raw_fd_ostream(StringRef Filename, std::error_code &EC, 511 sys::fs::OpenFlags Flags) 512 : raw_fd_ostream(getFD(Filename, EC, Flags), true) {} 513 514 /// FD is the file descriptor that this writes to. If ShouldClose is true, this 515 /// closes the file when the stream is destroyed. 516 raw_fd_ostream::raw_fd_ostream(int fd, bool shouldClose, bool unbuffered) 517 : raw_pwrite_stream(unbuffered), FD(fd), ShouldClose(shouldClose) { 518 if (FD < 0 ) { 519 ShouldClose = false; 520 return; 521 } 522 523 // Do not attempt to close stdout or stderr. We used to try to maintain the 524 // property that tools that support writing file to stdout should not also 525 // write informational output to stdout, but in practice we were never able to 526 // maintain this invariant. Many features have been added to LLVM and clang 527 // (-fdump-record-layouts, optimization remarks, etc) that print to stdout, so 528 // users must simply be aware that mixed output and remarks is a possibility. 529 if (FD <= STDERR_FILENO) 530 ShouldClose = false; 531 532 // Get the starting position. 533 off_t loc = ::lseek(FD, 0, SEEK_CUR); 534 #ifdef LLVM_ON_WIN32 535 // MSVCRT's _lseek(SEEK_CUR) doesn't return -1 for pipes. 536 sys::fs::file_status Status; 537 std::error_code EC = status(FD, Status); 538 SupportsSeeking = !EC && Status.type() == sys::fs::file_type::regular_file; 539 #else 540 SupportsSeeking = loc != (off_t)-1; 541 #endif 542 if (!SupportsSeeking) 543 pos = 0; 544 else 545 pos = static_cast<uint64_t>(loc); 546 } 547 548 raw_fd_ostream::~raw_fd_ostream() { 549 if (FD >= 0) { 550 flush(); 551 if (ShouldClose) { 552 if (auto EC = sys::Process::SafelyCloseFileDescriptor(FD)) 553 error_detected(EC); 554 } 555 } 556 557 #ifdef __MINGW32__ 558 // On mingw, global dtors should not call exit(). 559 // report_fatal_error() invokes exit(). We know report_fatal_error() 560 // might not write messages to stderr when any errors were detected 561 // on FD == 2. 562 if (FD == 2) return; 563 #endif 564 565 // If there are any pending errors, report them now. Clients wishing 566 // to avoid report_fatal_error calls should check for errors with 567 // has_error() and clear the error flag with clear_error() before 568 // destructing raw_ostream objects which may have errors. 569 if (has_error()) 570 report_fatal_error("IO failure on output stream: " + error().message(), 571 /*GenCrashDiag=*/false); 572 } 573 574 void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) { 575 assert(FD >= 0 && "File already closed."); 576 pos += Size; 577 578 // The maximum write size is limited to SSIZE_MAX because a write 579 // greater than SSIZE_MAX is implementation-defined in POSIX. 580 // Since SSIZE_MAX is not portable, we use SIZE_MAX >> 1 instead. 581 size_t MaxWriteSize = SIZE_MAX >> 1; 582 583 #if defined(__linux__) 584 // It is observed that Linux returns EINVAL for a very large write (>2G). 585 // Make it a reasonably small value. 586 MaxWriteSize = 1024 * 1024 * 1024; 587 #elif defined(LLVM_ON_WIN32) 588 // Writing a large size of output to Windows console returns ENOMEM. It seems 589 // that, prior to Windows 8, WriteFile() is redirecting to WriteConsole(), and 590 // the latter has a size limit (66000 bytes or less, depending on heap usage). 591 if (::_isatty(FD) && !RunningWindows8OrGreater()) 592 MaxWriteSize = 32767; 593 #endif 594 595 do { 596 size_t ChunkSize = std::min(Size, MaxWriteSize); 597 ssize_t ret = ::write(FD, Ptr, ChunkSize); 598 599 if (ret < 0) { 600 // If it's a recoverable error, swallow it and retry the write. 601 // 602 // Ideally we wouldn't ever see EAGAIN or EWOULDBLOCK here, since 603 // raw_ostream isn't designed to do non-blocking I/O. However, some 604 // programs, such as old versions of bjam, have mistakenly used 605 // O_NONBLOCK. For compatibility, emulate blocking semantics by 606 // spinning until the write succeeds. If you don't want spinning, 607 // don't use O_NONBLOCK file descriptors with raw_ostream. 608 if (errno == EINTR || errno == EAGAIN 609 #ifdef EWOULDBLOCK 610 || errno == EWOULDBLOCK 611 #endif 612 ) 613 continue; 614 615 // Otherwise it's a non-recoverable error. Note it and quit. 616 error_detected(std::error_code(errno, std::generic_category())); 617 break; 618 } 619 620 // The write may have written some or all of the data. Update the 621 // size and buffer pointer to reflect the remainder that needs 622 // to be written. If there are no bytes left, we're done. 623 Ptr += ret; 624 Size -= ret; 625 } while (Size > 0); 626 } 627 628 void raw_fd_ostream::close() { 629 assert(ShouldClose); 630 ShouldClose = false; 631 flush(); 632 if (auto EC = sys::Process::SafelyCloseFileDescriptor(FD)) 633 error_detected(EC); 634 FD = -1; 635 } 636 637 uint64_t raw_fd_ostream::seek(uint64_t off) { 638 assert(SupportsSeeking && "Stream does not support seeking!"); 639 flush(); 640 #ifdef LLVM_ON_WIN32 641 pos = ::_lseeki64(FD, off, SEEK_SET); 642 #elif defined(HAVE_LSEEK64) 643 pos = ::lseek64(FD, off, SEEK_SET); 644 #else 645 pos = ::lseek(FD, off, SEEK_SET); 646 #endif 647 if (pos == (uint64_t)-1) 648 error_detected(std::error_code(errno, std::generic_category())); 649 return pos; 650 } 651 652 void raw_fd_ostream::pwrite_impl(const char *Ptr, size_t Size, 653 uint64_t Offset) { 654 uint64_t Pos = tell(); 655 seek(Offset); 656 write(Ptr, Size); 657 seek(Pos); 658 } 659 660 size_t raw_fd_ostream::preferred_buffer_size() const { 661 #if !defined(_MSC_VER) && !defined(__MINGW32__) && !defined(__minix) 662 // Windows and Minix have no st_blksize. 663 assert(FD >= 0 && "File not yet open!"); 664 struct stat statbuf; 665 if (fstat(FD, &statbuf) != 0) 666 return 0; 667 668 // If this is a terminal, don't use buffering. Line buffering 669 // would be a more traditional thing to do, but it's not worth 670 // the complexity. 671 if (S_ISCHR(statbuf.st_mode) && isatty(FD)) 672 return 0; 673 // Return the preferred block size. 674 return statbuf.st_blksize; 675 #else 676 return raw_ostream::preferred_buffer_size(); 677 #endif 678 } 679 680 raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold, 681 bool bg) { 682 if (sys::Process::ColorNeedsFlush()) 683 flush(); 684 const char *colorcode = 685 (colors == SAVEDCOLOR) ? sys::Process::OutputBold(bg) 686 : sys::Process::OutputColor(colors, bold, bg); 687 if (colorcode) { 688 size_t len = strlen(colorcode); 689 write(colorcode, len); 690 // don't account colors towards output characters 691 pos -= len; 692 } 693 return *this; 694 } 695 696 raw_ostream &raw_fd_ostream::resetColor() { 697 if (sys::Process::ColorNeedsFlush()) 698 flush(); 699 const char *colorcode = sys::Process::ResetColor(); 700 if (colorcode) { 701 size_t len = strlen(colorcode); 702 write(colorcode, len); 703 // don't account colors towards output characters 704 pos -= len; 705 } 706 return *this; 707 } 708 709 raw_ostream &raw_fd_ostream::reverseColor() { 710 if (sys::Process::ColorNeedsFlush()) 711 flush(); 712 const char *colorcode = sys::Process::OutputReverse(); 713 if (colorcode) { 714 size_t len = strlen(colorcode); 715 write(colorcode, len); 716 // don't account colors towards output characters 717 pos -= len; 718 } 719 return *this; 720 } 721 722 bool raw_fd_ostream::is_displayed() const { 723 return sys::Process::FileDescriptorIsDisplayed(FD); 724 } 725 726 bool raw_fd_ostream::has_colors() const { 727 return sys::Process::FileDescriptorHasColors(FD); 728 } 729 730 //===----------------------------------------------------------------------===// 731 // outs(), errs(), nulls() 732 //===----------------------------------------------------------------------===// 733 734 /// outs() - This returns a reference to a raw_ostream for standard output. 735 /// Use it like: outs() << "foo" << "bar"; 736 raw_ostream &llvm::outs() { 737 // Set buffer settings to model stdout behavior. 738 std::error_code EC; 739 static raw_fd_ostream S("-", EC, sys::fs::F_None); 740 assert(!EC); 741 return S; 742 } 743 744 /// errs() - This returns a reference to a raw_ostream for standard error. 745 /// Use it like: errs() << "foo" << "bar"; 746 raw_ostream &llvm::errs() { 747 // Set standard error to be unbuffered by default. 748 static raw_fd_ostream S(STDERR_FILENO, false, true); 749 return S; 750 } 751 752 /// nulls() - This returns a reference to a raw_ostream which discards output. 753 raw_ostream &llvm::nulls() { 754 static raw_null_ostream S; 755 return S; 756 } 757 758 //===----------------------------------------------------------------------===// 759 // raw_string_ostream 760 //===----------------------------------------------------------------------===// 761 762 raw_string_ostream::~raw_string_ostream() { 763 flush(); 764 } 765 766 void raw_string_ostream::write_impl(const char *Ptr, size_t Size) { 767 OS.append(Ptr, Size); 768 } 769 770 //===----------------------------------------------------------------------===// 771 // raw_svector_ostream 772 //===----------------------------------------------------------------------===// 773 774 uint64_t raw_svector_ostream::current_pos() const { return OS.size(); } 775 776 void raw_svector_ostream::write_impl(const char *Ptr, size_t Size) { 777 OS.append(Ptr, Ptr + Size); 778 } 779 780 void raw_svector_ostream::pwrite_impl(const char *Ptr, size_t Size, 781 uint64_t Offset) { 782 memcpy(OS.data() + Offset, Ptr, Size); 783 } 784 785 //===----------------------------------------------------------------------===// 786 // raw_null_ostream 787 //===----------------------------------------------------------------------===// 788 789 raw_null_ostream::~raw_null_ostream() { 790 #ifndef NDEBUG 791 // ~raw_ostream asserts that the buffer is empty. This isn't necessary 792 // with raw_null_ostream, but it's better to have raw_null_ostream follow 793 // the rules than to change the rules just for raw_null_ostream. 794 flush(); 795 #endif 796 } 797 798 void raw_null_ostream::write_impl(const char *Ptr, size_t Size) { 799 } 800 801 uint64_t raw_null_ostream::current_pos() const { 802 return 0; 803 } 804 805 void raw_null_ostream::pwrite_impl(const char *Ptr, size_t Size, 806 uint64_t Offset) {} 807