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