raw_ostream.cpp 28 KB

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