1 //===--- raw_ostream.h - Raw output stream ----------------------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines the raw_ostream class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #ifndef LLVM_SUPPORT_RAW_OSTREAM_H 14 #define LLVM_SUPPORT_RAW_OSTREAM_H 15 16 #include "llvm/ADT/SmallVector.h" 17 #include "llvm/ADT/StringRef.h" 18 #include <cassert> 19 #include <cstddef> 20 #include <cstdint> 21 #include <cstring> 22 #include <string> 23 #include <system_error> 24 25 namespace llvm { 26 27 class formatv_object_base; 28 class format_object_base; 29 class FormattedString; 30 class FormattedNumber; 31 class FormattedBytes; 32 33 namespace sys { 34 namespace fs { 35 enum FileAccess : unsigned; 36 enum OpenFlags : unsigned; 37 enum CreationDisposition : unsigned; 38 } // end namespace fs 39 } // end namespace sys 40 41 /// This class implements an extremely fast bulk output stream that can *only* 42 /// output to a stream. It does not support seeking, reopening, rewinding, line 43 /// buffered disciplines etc. It is a simple buffer that outputs 44 /// a chunk at a time. 45 class raw_ostream { 46 private: 47 /// The buffer is handled in such a way that the buffer is 48 /// uninitialized, unbuffered, or out of space when OutBufCur >= 49 /// OutBufEnd. Thus a single comparison suffices to determine if we 50 /// need to take the slow path to write a single character. 51 /// 52 /// The buffer is in one of three states: 53 /// 1. Unbuffered (BufferMode == Unbuffered) 54 /// 1. Uninitialized (BufferMode != Unbuffered && OutBufStart == 0). 55 /// 2. Buffered (BufferMode != Unbuffered && OutBufStart != 0 && 56 /// OutBufEnd - OutBufStart >= 1). 57 /// 58 /// If buffered, then the raw_ostream owns the buffer if (BufferMode == 59 /// InternalBuffer); otherwise the buffer has been set via SetBuffer and is 60 /// managed by the subclass. 61 /// 62 /// If a subclass installs an external buffer using SetBuffer then it can wait 63 /// for a \see write_impl() call to handle the data which has been put into 64 /// this buffer. 65 char *OutBufStart, *OutBufEnd, *OutBufCur; 66 67 enum BufferKind { 68 Unbuffered = 0, 69 InternalBuffer, 70 ExternalBuffer 71 } BufferMode; 72 73 public: 74 // color order matches ANSI escape sequence, don't change 75 enum class Colors { 76 BLACK = 0, 77 RED, 78 GREEN, 79 YELLOW, 80 BLUE, 81 MAGENTA, 82 CYAN, 83 WHITE, 84 SAVEDCOLOR, 85 RESET, 86 }; 87 88 static const Colors BLACK = Colors::BLACK; 89 static const Colors RED = Colors::RED; 90 static const Colors GREEN = Colors::GREEN; 91 static const Colors YELLOW = Colors::YELLOW; 92 static const Colors BLUE = Colors::BLUE; 93 static const Colors MAGENTA = Colors::MAGENTA; 94 static const Colors CYAN = Colors::CYAN; 95 static const Colors WHITE = Colors::WHITE; 96 static const Colors SAVEDCOLOR = Colors::SAVEDCOLOR; 97 static const Colors RESET = Colors::RESET; 98 99 explicit raw_ostream(bool unbuffered = false) 100 : BufferMode(unbuffered ? Unbuffered : InternalBuffer) { 101 // Start out ready to flush. 102 OutBufStart = OutBufEnd = OutBufCur = nullptr; 103 } 104 105 raw_ostream(const raw_ostream &) = delete; 106 void operator=(const raw_ostream &) = delete; 107 108 virtual ~raw_ostream(); 109 110 /// tell - Return the current offset with the file. 111 uint64_t tell() const { return current_pos() + GetNumBytesInBuffer(); } 112 113 //===--------------------------------------------------------------------===// 114 // Configuration Interface 115 //===--------------------------------------------------------------------===// 116 117 /// Set the stream to be buffered, with an automatically determined buffer 118 /// size. 119 void SetBuffered(); 120 121 /// Set the stream to be buffered, using the specified buffer size. 122 void SetBufferSize(size_t Size) { 123 flush(); 124 SetBufferAndMode(new char[Size], Size, InternalBuffer); 125 } 126 127 size_t GetBufferSize() const { 128 // If we're supposed to be buffered but haven't actually gotten around 129 // to allocating the buffer yet, return the value that would be used. 130 if (BufferMode != Unbuffered && OutBufStart == nullptr) 131 return preferred_buffer_size(); 132 133 // Otherwise just return the size of the allocated buffer. 134 return OutBufEnd - OutBufStart; 135 } 136 137 /// Set the stream to be unbuffered. When unbuffered, the stream will flush 138 /// after every write. This routine will also flush the buffer immediately 139 /// when the stream is being set to unbuffered. 140 void SetUnbuffered() { 141 flush(); 142 SetBufferAndMode(nullptr, 0, Unbuffered); 143 } 144 145 size_t GetNumBytesInBuffer() const { 146 return OutBufCur - OutBufStart; 147 } 148 149 //===--------------------------------------------------------------------===// 150 // Data Output Interface 151 //===--------------------------------------------------------------------===// 152 153 void flush() { 154 if (OutBufCur != OutBufStart) 155 flush_nonempty(); 156 } 157 158 raw_ostream &operator<<(char C) { 159 if (OutBufCur >= OutBufEnd) 160 return write(C); 161 *OutBufCur++ = C; 162 return *this; 163 } 164 165 raw_ostream &operator<<(unsigned char C) { 166 if (OutBufCur >= OutBufEnd) 167 return write(C); 168 *OutBufCur++ = C; 169 return *this; 170 } 171 172 raw_ostream &operator<<(signed char C) { 173 if (OutBufCur >= OutBufEnd) 174 return write(C); 175 *OutBufCur++ = C; 176 return *this; 177 } 178 179 raw_ostream &operator<<(StringRef Str) { 180 // Inline fast path, particularly for strings with a known length. 181 size_t Size = Str.size(); 182 183 // Make sure we can use the fast path. 184 if (Size > (size_t)(OutBufEnd - OutBufCur)) 185 return write(Str.data(), Size); 186 187 if (Size) { 188 memcpy(OutBufCur, Str.data(), Size); 189 OutBufCur += Size; 190 } 191 return *this; 192 } 193 194 raw_ostream &operator<<(const char *Str) { 195 // Inline fast path, particularly for constant strings where a sufficiently 196 // smart compiler will simplify strlen. 197 198 return this->operator<<(StringRef(Str)); 199 } 200 201 raw_ostream &operator<<(const std::string &Str) { 202 // Avoid the fast path, it would only increase code size for a marginal win. 203 return write(Str.data(), Str.length()); 204 } 205 206 raw_ostream &operator<<(const SmallVectorImpl<char> &Str) { 207 return write(Str.data(), Str.size()); 208 } 209 210 raw_ostream &operator<<(unsigned long N); 211 raw_ostream &operator<<(long N); 212 raw_ostream &operator<<(unsigned long long N); 213 raw_ostream &operator<<(long long N); 214 raw_ostream &operator<<(const void *P); 215 216 raw_ostream &operator<<(unsigned int N) { 217 return this->operator<<(static_cast<unsigned long>(N)); 218 } 219 220 raw_ostream &operator<<(int N) { 221 return this->operator<<(static_cast<long>(N)); 222 } 223 224 raw_ostream &operator<<(double N); 225 226 /// Output \p N in hexadecimal, without any prefix or padding. 227 raw_ostream &write_hex(unsigned long long N); 228 229 // Change the foreground color of text. 230 raw_ostream &operator<<(Colors C); 231 232 /// Output a formatted UUID with dash separators. 233 using uuid_t = uint8_t[16]; 234 raw_ostream &write_uuid(const uuid_t UUID); 235 236 /// Output \p Str, turning '\\', '\t', '\n', '"', and anything that doesn't 237 /// satisfy llvm::isPrint into an escape sequence. 238 raw_ostream &write_escaped(StringRef Str, bool UseHexEscapes = false); 239 240 raw_ostream &write(unsigned char C); 241 raw_ostream &write(const char *Ptr, size_t Size); 242 243 // Formatted output, see the format() function in Support/Format.h. 244 raw_ostream &operator<<(const format_object_base &Fmt); 245 246 // Formatted output, see the leftJustify() function in Support/Format.h. 247 raw_ostream &operator<<(const FormattedString &); 248 249 // Formatted output, see the formatHex() function in Support/Format.h. 250 raw_ostream &operator<<(const FormattedNumber &); 251 252 // Formatted output, see the formatv() function in Support/FormatVariadic.h. 253 raw_ostream &operator<<(const formatv_object_base &); 254 255 // Formatted output, see the format_bytes() function in Support/Format.h. 256 raw_ostream &operator<<(const FormattedBytes &); 257 258 /// indent - Insert 'NumSpaces' spaces. 259 raw_ostream &indent(unsigned NumSpaces); 260 261 /// write_zeros - Insert 'NumZeros' nulls. 262 raw_ostream &write_zeros(unsigned NumZeros); 263 264 /// Changes the foreground color of text that will be output from this point 265 /// forward. 266 /// @param Color ANSI color to use, the special SAVEDCOLOR can be used to 267 /// change only the bold attribute, and keep colors untouched 268 /// @param Bold bold/brighter text, default false 269 /// @param BG if true change the background, default: change foreground 270 /// @returns itself so it can be used within << invocations 271 virtual raw_ostream &changeColor(enum Colors Color, 272 bool Bold = false, 273 bool BG = false) { 274 (void)Color; 275 (void)Bold; 276 (void)BG; 277 return *this; 278 } 279 280 /// Resets the colors to terminal defaults. Call this when you are done 281 /// outputting colored text, or before program exit. 282 virtual raw_ostream &resetColor() { return *this; } 283 284 /// Reverses the foreground and background colors. 285 virtual raw_ostream &reverseColor() { return *this; } 286 287 /// This function determines if this stream is connected to a "tty" or 288 /// "console" window. That is, the output would be displayed to the user 289 /// rather than being put on a pipe or stored in a file. 290 virtual bool is_displayed() const { return false; } 291 292 /// This function determines if this stream is displayed and supports colors. 293 virtual bool has_colors() const { return is_displayed(); } 294 295 // Enable or disable colors. Once disable_colors() is called, 296 // changeColor() has no effect until enable_colors() is called. 297 virtual void enable_colors(bool /*enable*/) {} 298 299 //===--------------------------------------------------------------------===// 300 // Subclass Interface 301 //===--------------------------------------------------------------------===// 302 303 private: 304 /// The is the piece of the class that is implemented by subclasses. This 305 /// writes the \p Size bytes starting at 306 /// \p Ptr to the underlying stream. 307 /// 308 /// This function is guaranteed to only be called at a point at which it is 309 /// safe for the subclass to install a new buffer via SetBuffer. 310 /// 311 /// \param Ptr The start of the data to be written. For buffered streams this 312 /// is guaranteed to be the start of the buffer. 313 /// 314 /// \param Size The number of bytes to be written. 315 /// 316 /// \invariant { Size > 0 } 317 virtual void write_impl(const char *Ptr, size_t Size) = 0; 318 319 /// Return the current position within the stream, not counting the bytes 320 /// currently in the buffer. 321 virtual uint64_t current_pos() const = 0; 322 323 protected: 324 /// Use the provided buffer as the raw_ostream buffer. This is intended for 325 /// use only by subclasses which can arrange for the output to go directly 326 /// into the desired output buffer, instead of being copied on each flush. 327 void SetBuffer(char *BufferStart, size_t Size) { 328 SetBufferAndMode(BufferStart, Size, ExternalBuffer); 329 } 330 331 /// Return an efficient buffer size for the underlying output mechanism. 332 virtual size_t preferred_buffer_size() const; 333 334 /// Return the beginning of the current stream buffer, or 0 if the stream is 335 /// unbuffered. 336 const char *getBufferStart() const { return OutBufStart; } 337 338 //===--------------------------------------------------------------------===// 339 // Private Interface 340 //===--------------------------------------------------------------------===// 341 private: 342 /// Install the given buffer and mode. 343 void SetBufferAndMode(char *BufferStart, size_t Size, BufferKind Mode); 344 345 /// Flush the current buffer, which is known to be non-empty. This outputs the 346 /// currently buffered data and resets the buffer to empty. 347 void flush_nonempty(); 348 349 /// Copy data into the buffer. Size must not be greater than the number of 350 /// unused bytes in the buffer. 351 void copy_to_buffer(const char *Ptr, size_t Size); 352 353 virtual void anchor(); 354 }; 355 356 /// An abstract base class for streams implementations that also support a 357 /// pwrite operation. This is useful for code that can mostly stream out data, 358 /// but needs to patch in a header that needs to know the output size. 359 class raw_pwrite_stream : public raw_ostream { 360 virtual void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) = 0; 361 void anchor() override; 362 363 public: 364 explicit raw_pwrite_stream(bool Unbuffered = false) 365 : raw_ostream(Unbuffered) {} 366 void pwrite(const char *Ptr, size_t Size, uint64_t Offset) { 367 #ifndef NDEBUG 368 uint64_t Pos = tell(); 369 // /dev/null always reports a pos of 0, so we cannot perform this check 370 // in that case. 371 if (Pos) 372 assert(Size + Offset <= Pos && "We don't support extending the stream"); 373 #endif 374 pwrite_impl(Ptr, Size, Offset); 375 } 376 }; 377 378 //===----------------------------------------------------------------------===// 379 // File Output Streams 380 //===----------------------------------------------------------------------===// 381 382 /// A raw_ostream that writes to a file descriptor. 383 /// 384 class raw_fd_ostream : public raw_pwrite_stream { 385 int FD; 386 bool ShouldClose; 387 bool SupportsSeeking; 388 bool ColorEnabled = true; 389 390 #ifdef _WIN32 391 /// True if this fd refers to a Windows console device. Mintty and other 392 /// terminal emulators are TTYs, but they are not consoles. 393 bool IsWindowsConsole = false; 394 #endif 395 396 std::error_code EC; 397 398 uint64_t pos; 399 400 /// See raw_ostream::write_impl. 401 void write_impl(const char *Ptr, size_t Size) override; 402 403 void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override; 404 405 /// Return the current position within the stream, not counting the bytes 406 /// currently in the buffer. 407 uint64_t current_pos() const override { return pos; } 408 409 /// Determine an efficient buffer size. 410 size_t preferred_buffer_size() const override; 411 412 /// Set the flag indicating that an output error has been encountered. 413 void error_detected(std::error_code EC) { this->EC = EC; } 414 415 void anchor() override; 416 417 public: 418 /// Open the specified file for writing. If an error occurs, information 419 /// about the error is put into EC, and the stream should be immediately 420 /// destroyed; 421 /// \p Flags allows optional flags to control how the file will be opened. 422 /// 423 /// As a special case, if Filename is "-", then the stream will use 424 /// STDOUT_FILENO instead of opening a file. This will not close the stdout 425 /// descriptor. 426 raw_fd_ostream(StringRef Filename, std::error_code &EC); 427 raw_fd_ostream(StringRef Filename, std::error_code &EC, 428 sys::fs::CreationDisposition Disp); 429 raw_fd_ostream(StringRef Filename, std::error_code &EC, 430 sys::fs::FileAccess Access); 431 raw_fd_ostream(StringRef Filename, std::error_code &EC, 432 sys::fs::OpenFlags Flags); 433 raw_fd_ostream(StringRef Filename, std::error_code &EC, 434 sys::fs::CreationDisposition Disp, sys::fs::FileAccess Access, 435 sys::fs::OpenFlags Flags); 436 437 /// FD is the file descriptor that this writes to. If ShouldClose is true, 438 /// this closes the file when the stream is destroyed. If FD is for stdout or 439 /// stderr, it will not be closed. 440 raw_fd_ostream(int fd, bool shouldClose, bool unbuffered=false); 441 442 ~raw_fd_ostream() override; 443 444 /// Manually flush the stream and close the file. Note that this does not call 445 /// fsync. 446 void close(); 447 448 bool supportsSeeking() { return SupportsSeeking; } 449 450 /// Flushes the stream and repositions the underlying file descriptor position 451 /// to the offset specified from the beginning of the file. 452 uint64_t seek(uint64_t off); 453 454 raw_ostream &changeColor(enum Colors colors, bool bold=false, 455 bool bg=false) override; 456 raw_ostream &resetColor() override; 457 458 raw_ostream &reverseColor() override; 459 460 bool is_displayed() const override; 461 462 bool has_colors() const override; 463 464 void enable_colors(bool enable) override { ColorEnabled = enable; } 465 466 std::error_code error() const { return EC; } 467 468 /// Return the value of the flag in this raw_fd_ostream indicating whether an 469 /// output error has been encountered. 470 /// This doesn't implicitly flush any pending output. Also, it doesn't 471 /// guarantee to detect all errors unless the stream has been closed. 472 bool has_error() const { return bool(EC); } 473 474 /// Set the flag read by has_error() to false. If the error flag is set at the 475 /// time when this raw_ostream's destructor is called, report_fatal_error is 476 /// called to report the error. Use clear_error() after handling the error to 477 /// avoid this behavior. 478 /// 479 /// "Errors should never pass silently. 480 /// Unless explicitly silenced." 481 /// - from The Zen of Python, by Tim Peters 482 /// 483 void clear_error() { EC = std::error_code(); } 484 }; 485 486 /// This returns a reference to a raw_ostream for standard output. Use it like: 487 /// outs() << "foo" << "bar"; 488 raw_ostream &outs(); 489 490 /// This returns a reference to a raw_ostream for standard error. Use it like: 491 /// errs() << "foo" << "bar"; 492 raw_ostream &errs(); 493 494 /// This returns a reference to a raw_ostream which simply discards output. 495 raw_ostream &nulls(); 496 497 //===----------------------------------------------------------------------===// 498 // Output Stream Adaptors 499 //===----------------------------------------------------------------------===// 500 501 /// A raw_ostream that writes to an std::string. This is a simple adaptor 502 /// class. This class does not encounter output errors. 503 class raw_string_ostream : public raw_ostream { 504 std::string &OS; 505 506 /// See raw_ostream::write_impl. 507 void write_impl(const char *Ptr, size_t Size) override; 508 509 /// Return the current position within the stream, not counting the bytes 510 /// currently in the buffer. 511 uint64_t current_pos() const override { return OS.size(); } 512 513 public: 514 explicit raw_string_ostream(std::string &O) : OS(O) {} 515 ~raw_string_ostream() override; 516 517 /// Flushes the stream contents to the target string and returns the string's 518 /// reference. 519 std::string& str() { 520 flush(); 521 return OS; 522 } 523 }; 524 525 /// A raw_ostream that writes to an SmallVector or SmallString. This is a 526 /// simple adaptor class. This class does not encounter output errors. 527 /// raw_svector_ostream operates without a buffer, delegating all memory 528 /// management to the SmallString. Thus the SmallString is always up-to-date, 529 /// may be used directly and there is no need to call flush(). 530 class raw_svector_ostream : public raw_pwrite_stream { 531 SmallVectorImpl<char> &OS; 532 533 /// See raw_ostream::write_impl. 534 void write_impl(const char *Ptr, size_t Size) override; 535 536 void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override; 537 538 /// Return the current position within the stream. 539 uint64_t current_pos() const override; 540 541 public: 542 /// Construct a new raw_svector_ostream. 543 /// 544 /// \param O The vector to write to; this should generally have at least 128 545 /// bytes free to avoid any extraneous memory overhead. 546 explicit raw_svector_ostream(SmallVectorImpl<char> &O) : OS(O) { 547 SetUnbuffered(); 548 } 549 550 ~raw_svector_ostream() override = default; 551 552 void flush() = delete; 553 554 /// Return a StringRef for the vector contents. 555 StringRef str() { return StringRef(OS.data(), OS.size()); } 556 }; 557 558 /// A raw_ostream that discards all output. 559 class raw_null_ostream : public raw_pwrite_stream { 560 /// See raw_ostream::write_impl. 561 void write_impl(const char *Ptr, size_t size) override; 562 void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override; 563 564 /// Return the current position within the stream, not counting the bytes 565 /// currently in the buffer. 566 uint64_t current_pos() const override; 567 568 public: 569 explicit raw_null_ostream() = default; 570 ~raw_null_ostream() override; 571 }; 572 573 class buffer_ostream : public raw_svector_ostream { 574 raw_ostream &OS; 575 SmallVector<char, 0> Buffer; 576 577 virtual void anchor() override; 578 579 public: 580 buffer_ostream(raw_ostream &OS) : raw_svector_ostream(Buffer), OS(OS) {} 581 ~buffer_ostream() override { OS << str(); } 582 }; 583 584 } // end namespace llvm 585 586 #endif // LLVM_SUPPORT_RAW_OSTREAM_H 587