raw_ostream.cpp 24 KB

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