raw_ostream.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  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/MathExtras.h"
  23. #include "llvm/Support/Process.h"
  24. #include "llvm/Support/Program.h"
  25. #include <cctype>
  26. #include <cerrno>
  27. #include <ios>
  28. #include <sys/stat.h>
  29. #include <system_error>
  30. // <fcntl.h> may provide O_BINARY.
  31. #if defined(HAVE_FCNTL_H)
  32. # include <fcntl.h>
  33. #endif
  34. #if defined(HAVE_UNISTD_H)
  35. # include <unistd.h>
  36. #endif
  37. #if defined(HAVE_SYS_UIO_H) && defined(HAVE_WRITEV)
  38. # include <sys/uio.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. using namespace llvm;
  56. raw_ostream::~raw_ostream() {
  57. // raw_ostream's subclasses should take care to flush the buffer
  58. // in their destructors.
  59. assert(OutBufCur == OutBufStart &&
  60. "raw_ostream destructor called with non-empty buffer!");
  61. if (BufferMode == InternalBuffer)
  62. delete [] OutBufStart;
  63. }
  64. // An out of line virtual method to provide a home for the class vtable.
  65. void raw_ostream::handle() {}
  66. size_t raw_ostream::preferred_buffer_size() const {
  67. // BUFSIZ is intended to be a reasonable default.
  68. return BUFSIZ;
  69. }
  70. void raw_ostream::SetBuffered() {
  71. // Ask the subclass to determine an appropriate buffer size.
  72. if (size_t Size = preferred_buffer_size())
  73. SetBufferSize(Size);
  74. else
  75. // It may return 0, meaning this stream should be unbuffered.
  76. SetUnbuffered();
  77. }
  78. void raw_ostream::SetBufferAndMode(_In_opt_ char *BufferStart, size_t Size,
  79. BufferKind Mode) {
  80. assert(((Mode == Unbuffered && !BufferStart && Size == 0) ||
  81. (Mode != Unbuffered && BufferStart && Size != 0)) &&
  82. "stream must be unbuffered or have at least one byte");
  83. // Make sure the current buffer is free of content (we can't flush here; the
  84. // child buffer management logic will be in write_impl).
  85. assert(GetNumBytesInBuffer() == 0 && "Current buffer is non-empty!");
  86. if (BufferMode == InternalBuffer)
  87. delete [] OutBufStart;
  88. OutBufStart = BufferStart;
  89. OutBufEnd = OutBufStart+Size;
  90. OutBufCur = OutBufStart;
  91. BufferMode = Mode;
  92. assert(OutBufStart <= OutBufEnd && "Invalid size!");
  93. }
  94. raw_ostream &raw_ostream::operator<<(unsigned long N) {
  95. // HLSL Change Starts - Handle non-base10 printing
  96. if (writeBase != 10) {
  97. *this << '0';
  98. if (writeBase == 16)
  99. *this << 'x';
  100. return write_base((unsigned long long)N);
  101. }
  102. // HLSL Change Ends
  103. // Zero is a special case.
  104. if (N == 0)
  105. return *this << '0';
  106. char NumberBuffer[20];
  107. char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
  108. char *CurPtr = EndPtr;
  109. while (N) {
  110. *--CurPtr = '0' + char(N % 10);
  111. N /= 10;
  112. }
  113. return write(CurPtr, EndPtr-CurPtr);
  114. }
  115. raw_ostream &raw_ostream::operator<<(long N) {
  116. if (N < 0 && writeBase == 10) {
  117. *this << '-';
  118. // Avoid undefined behavior on LONG_MIN with a cast.
  119. N = -(unsigned long)N;
  120. }
  121. return this->operator<<(static_cast<unsigned long>(N));
  122. }
  123. raw_ostream &raw_ostream::operator<<(unsigned long long N) {
  124. // Output using 32-bit div/mod when possible.
  125. if (N == static_cast<unsigned long>(N))
  126. return this->operator<<(static_cast<unsigned long>(N));
  127. // HLSL Change Starts - Handle non-base10 printing
  128. if (writeBase != 10) {
  129. *this << '0';
  130. if (writeBase == 16)
  131. *this << 'x';
  132. return write_base((unsigned long long)N);
  133. }
  134. // HLSL Change Ends
  135. char NumberBuffer[20];
  136. char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
  137. char *CurPtr = EndPtr;
  138. while (N) {
  139. *--CurPtr = '0' + char(N % 10);
  140. N /= 10;
  141. }
  142. return write(CurPtr, EndPtr-CurPtr);
  143. }
  144. raw_ostream &raw_ostream::operator<<(long long N) {
  145. if (N < 0 && writeBase == 10) {
  146. *this << '-';
  147. // Avoid undefined behavior on INT64_MIN with a cast.
  148. N = -(unsigned long long)N;
  149. }
  150. return this->operator<<(static_cast<unsigned long long>(N));
  151. }
  152. // HLSL Change Starts - Generalize non-base10 printing.
  153. raw_ostream &raw_ostream::write_hex(unsigned long long N) {
  154. int oldBase = writeBase;
  155. writeBase = 16;
  156. raw_ostream &rv = write_base(N);
  157. writeBase = oldBase;
  158. return rv;
  159. }
  160. raw_ostream &raw_ostream::write_base(unsigned long long N) {
  161. // Zero is a special case.
  162. if (N == 0)
  163. return *this << '0';
  164. char NumberBuffer[20];
  165. char *EndPtr = NumberBuffer + sizeof(NumberBuffer);
  166. char *CurPtr = EndPtr;
  167. while (N) {
  168. uintptr_t x = N % writeBase;
  169. *--CurPtr = (x < 10 ? '0' + x : 'a' + x - 10);
  170. N /= writeBase;
  171. }
  172. return write(CurPtr, EndPtr - CurPtr);
  173. }
  174. // HLSL Change Ends
  175. raw_ostream &raw_ostream::write_escaped(StringRef Str,
  176. bool UseHexEscapes) {
  177. for (unsigned i = 0, e = Str.size(); i != e; ++i) {
  178. unsigned char c = Str[i];
  179. switch (c) {
  180. case '\\':
  181. *this << '\\' << '\\';
  182. break;
  183. case '\t':
  184. *this << '\\' << 't';
  185. break;
  186. case '\n':
  187. *this << '\\' << 'n';
  188. break;
  189. case '"':
  190. *this << '\\' << '"';
  191. break;
  192. default:
  193. if (std::isprint(c)) {
  194. *this << c;
  195. break;
  196. }
  197. // Write out the escaped representation.
  198. if (UseHexEscapes) {
  199. *this << '\\' << 'x';
  200. *this << hexdigit((c >> 4 & 0xF));
  201. *this << hexdigit((c >> 0) & 0xF);
  202. } else {
  203. // Always use a full 3-character octal escape.
  204. *this << '\\';
  205. *this << char('0' + ((c >> 6) & 7));
  206. *this << char('0' + ((c >> 3) & 7));
  207. *this << char('0' + ((c >> 0) & 7));
  208. }
  209. }
  210. }
  211. return *this;
  212. }
  213. raw_ostream &raw_ostream::operator<<(const void *P) {
  214. *this << '0' << 'x';
  215. return write_hex((uintptr_t) P);
  216. }
  217. raw_ostream &raw_ostream::operator<<(double N) {
  218. #ifdef _WIN32
  219. // On MSVCRT and compatible, output of %e is incompatible to Posix
  220. // by default. Number of exponent digits should be at least 2. "%+03d"
  221. // FIXME: Implement our formatter to here or Support/Format.h!
  222. #if __cplusplus >= 201103L && defined(__MINGW32__)
  223. // FIXME: It should be generic to C++11.
  224. if (N == 0.0 && std::signbit(N))
  225. return *this << "-0.000000e+00";
  226. #else
  227. int fpcl = _fpclass(N);
  228. // negative zero
  229. if (fpcl == _FPCLASS_NZ)
  230. return *this << "-0.000000e+00";
  231. #endif
  232. char buf[16];
  233. unsigned len;
  234. len = format("%e", N).snprint(buf, sizeof(buf));
  235. if (len <= sizeof(buf) - 2) {
  236. if (len >= 5 && buf[len - 5] == 'e' && buf[len - 3] == '0') {
  237. int cs = buf[len - 4];
  238. if (cs == '+' || cs == '-') {
  239. int c1 = buf[len - 2];
  240. int c0 = buf[len - 1];
  241. if (isdigit(static_cast<unsigned char>(c1)) &&
  242. isdigit(static_cast<unsigned char>(c0))) {
  243. // Trim leading '0': "...e+012" -> "...e+12\0"
  244. buf[len - 3] = c1;
  245. buf[len - 2] = c0;
  246. buf[--len] = 0;
  247. }
  248. }
  249. }
  250. return this->operator<<(buf);
  251. }
  252. #endif
  253. return this->operator<<(format("%e", N));
  254. }
  255. void raw_ostream::flush_nonempty() {
  256. assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty.");
  257. size_t Length = OutBufCur - OutBufStart;
  258. OutBufCur = OutBufStart;
  259. write_impl(OutBufStart, Length);
  260. }
  261. raw_ostream &raw_ostream::write(unsigned char C) {
  262. // Group exceptional cases into a single branch.
  263. if (LLVM_UNLIKELY(OutBufCur >= OutBufEnd)) {
  264. if (LLVM_UNLIKELY(!OutBufStart)) {
  265. if (BufferMode == Unbuffered) {
  266. write_impl(reinterpret_cast<char*>(&C), 1);
  267. return *this;
  268. }
  269. // Set up a buffer and start over.
  270. SetBuffered();
  271. return write(C);
  272. }
  273. flush_nonempty();
  274. }
  275. *OutBufCur++ = C;
  276. return *this;
  277. }
  278. raw_ostream &raw_ostream::write(const char *Ptr, size_t Size) {
  279. // Group exceptional cases into a single branch.
  280. if (LLVM_UNLIKELY(size_t(OutBufEnd - OutBufCur) < Size)) {
  281. if (LLVM_UNLIKELY(!OutBufStart)) {
  282. if (BufferMode == Unbuffered) {
  283. write_impl(Ptr, Size);
  284. return *this;
  285. }
  286. // Set up a buffer and start over.
  287. SetBuffered();
  288. return write(Ptr, Size);
  289. }
  290. size_t NumBytes = OutBufEnd - OutBufCur;
  291. // If the buffer is empty at this point we have a string that is larger
  292. // than the buffer. Directly write the chunk that is a multiple of the
  293. // preferred buffer size and put the remainder in the buffer.
  294. if (LLVM_UNLIKELY(OutBufCur == OutBufStart)) {
  295. assert(NumBytes != 0 && "undefined behavior");
  296. size_t BytesToWrite = Size - (Size % NumBytes);
  297. write_impl(Ptr, BytesToWrite);
  298. size_t BytesRemaining = Size - BytesToWrite;
  299. if (BytesRemaining > size_t(OutBufEnd - OutBufCur)) {
  300. // Too much left over to copy into our buffer.
  301. return write(Ptr + BytesToWrite, BytesRemaining);
  302. }
  303. copy_to_buffer(Ptr + BytesToWrite, BytesRemaining);
  304. return *this;
  305. }
  306. // We don't have enough space in the buffer to fit the string in. Insert as
  307. // much as possible, flush and start over with the remainder.
  308. copy_to_buffer(Ptr, NumBytes);
  309. flush_nonempty();
  310. return write(Ptr + NumBytes, Size - NumBytes);
  311. }
  312. copy_to_buffer(Ptr, Size);
  313. return *this;
  314. }
  315. void raw_ostream::copy_to_buffer(const char *Ptr, size_t Size) {
  316. assert(Size <= size_t(OutBufEnd - OutBufCur) && "Buffer overrun!");
  317. // Handle short strings specially, memcpy isn't very good at very short
  318. // strings.
  319. switch (Size) {
  320. case 4: OutBufCur[3] = Ptr[3]; // FALL THROUGH
  321. case 3: OutBufCur[2] = Ptr[2]; // FALL THROUGH
  322. case 2: OutBufCur[1] = Ptr[1]; // FALL THROUGH
  323. case 1: OutBufCur[0] = Ptr[0]; // FALL THROUGH
  324. case 0: break;
  325. default:
  326. memcpy(OutBufCur, Ptr, Size);
  327. break;
  328. }
  329. OutBufCur += Size;
  330. }
  331. // Formatted output.
  332. raw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) {
  333. // If we have more than a few bytes left in our output buffer, try
  334. // formatting directly onto its end.
  335. size_t NextBufferSize = 127;
  336. size_t BufferBytesLeft = OutBufEnd - OutBufCur;
  337. if (BufferBytesLeft > 3) {
  338. size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft);
  339. // Common case is that we have plenty of space.
  340. if (BytesUsed <= BufferBytesLeft) {
  341. OutBufCur += BytesUsed;
  342. return *this;
  343. }
  344. // Otherwise, we overflowed and the return value tells us the size to try
  345. // again with.
  346. NextBufferSize = BytesUsed;
  347. }
  348. // If we got here, we didn't have enough space in the output buffer for the
  349. // string. Try printing into a SmallVector that is resized to have enough
  350. // space. Iterate until we win.
  351. SmallVector<char, 128> V;
  352. while (1) {
  353. V.resize(NextBufferSize);
  354. // Try formatting into the SmallVector.
  355. size_t BytesUsed = Fmt.print(V.data(), NextBufferSize);
  356. // If BytesUsed fit into the vector, we win.
  357. if (BytesUsed <= NextBufferSize)
  358. return write(V.data(), BytesUsed);
  359. // Otherwise, try again with a new size.
  360. assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?");
  361. NextBufferSize = BytesUsed;
  362. }
  363. }
  364. raw_ostream &raw_ostream::operator<<(const FormattedString &FS) {
  365. unsigned Len = FS.Str.size();
  366. int PadAmount = FS.Width - Len;
  367. if (FS.RightJustify && (PadAmount > 0))
  368. this->indent(PadAmount);
  369. this->operator<<(FS.Str);
  370. if (!FS.RightJustify && (PadAmount > 0))
  371. this->indent(PadAmount);
  372. return *this;
  373. }
  374. raw_ostream &raw_ostream::operator<<(const FormattedNumber &FN) {
  375. if (FN.Hex) {
  376. unsigned Nibbles = (64 - countLeadingZeros(FN.HexValue)+3)/4;
  377. unsigned PrefixChars = FN.HexPrefix ? 2 : 0;
  378. unsigned Width = std::max(FN.Width, Nibbles + PrefixChars);
  379. char NumberBuffer[20] = "0x0000000000000000";
  380. if (!FN.HexPrefix)
  381. NumberBuffer[1] = '0';
  382. char *EndPtr = NumberBuffer+Width;
  383. char *CurPtr = EndPtr;
  384. const char A = FN.Upper ? 'A' : 'a';
  385. unsigned long long N = FN.HexValue;
  386. while (N) {
  387. uintptr_t x = N % 16;
  388. assert(CurPtr > NumberBuffer && "else FN values inconsistent"); // HLSL Change
  389. _Analysis_assume_(CurPtr > NumberBuffer); // HLSL Change
  390. *--CurPtr = (x < 10 ? '0' + x : A + x - 10);
  391. N /= 16;
  392. }
  393. return write(NumberBuffer, Width);
  394. } else {
  395. // Zero is a special case.
  396. if (FN.DecValue == 0) {
  397. this->indent(FN.Width-1);
  398. return *this << '0';
  399. }
  400. char NumberBuffer[32];
  401. char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
  402. char *CurPtr = EndPtr;
  403. bool Neg = (FN.DecValue < 0);
  404. uint64_t N = Neg ? -static_cast<uint64_t>(FN.DecValue) : FN.DecValue;
  405. while (N) {
  406. *--CurPtr = '0' + char(N % 10);
  407. N /= 10;
  408. }
  409. int Len = EndPtr - CurPtr;
  410. int Pad = FN.Width - Len;
  411. if (Neg)
  412. --Pad;
  413. if (Pad > 0)
  414. this->indent(Pad);
  415. if (Neg)
  416. *this << '-';
  417. return write(CurPtr, Len);
  418. }
  419. }
  420. // HLSL Change Starts - Add handling of numerical base IO manipulators.
  421. raw_ostream &raw_ostream::
  422. operator<<(std::ios_base &(__cdecl*iomanip)(std::ios_base &)) {
  423. if (iomanip == std::hex)
  424. writeBase = 16;
  425. else if (iomanip == std::oct)
  426. writeBase = 8;
  427. else
  428. writeBase = 10;
  429. return *this;
  430. }
  431. // HLSL Change Ends
  432. /// indent - Insert 'NumSpaces' spaces.
  433. raw_ostream &raw_ostream::indent(unsigned NumSpaces) {
  434. static const char Spaces[] = " "
  435. " "
  436. " ";
  437. // Usually the indentation is small, handle it with a fastpath.
  438. if (NumSpaces < array_lengthof(Spaces))
  439. return write(Spaces, NumSpaces);
  440. while (NumSpaces) {
  441. unsigned NumToWrite = std::min(NumSpaces,
  442. (unsigned)array_lengthof(Spaces)-1);
  443. write(Spaces, NumToWrite);
  444. NumSpaces -= NumToWrite;
  445. }
  446. return *this;
  447. }
  448. //===----------------------------------------------------------------------===//
  449. // Formatted Output
  450. //===----------------------------------------------------------------------===//
  451. // Out of line virtual method.
  452. void format_object_base::home() {
  453. }
  454. //===----------------------------------------------------------------------===//
  455. // raw_fd_ostream
  456. //===----------------------------------------------------------------------===//
  457. static int getFD(StringRef Filename, std::error_code &EC,
  458. sys::fs::OpenFlags Flags) {
  459. // Handle "-" as stdout. Note that when we do this, we consider ourself
  460. // the owner of stdout. This means that we can do things like close the
  461. // file descriptor when we're done and set the "binary" flag globally.
  462. if (Filename == "-") {
  463. EC = std::error_code();
  464. // If user requested binary then put stdout into binary mode if
  465. // possible.
  466. if (!(Flags & sys::fs::F_Text))
  467. sys::ChangeStdoutToBinary();
  468. return STDOUT_FILENO;
  469. }
  470. int FD;
  471. EC = sys::fs::openFileForWrite(Filename, FD, Flags);
  472. if (EC)
  473. return -1;
  474. return FD;
  475. }
  476. raw_fd_ostream::raw_fd_ostream(StringRef Filename, std::error_code &EC,
  477. sys::fs::OpenFlags Flags)
  478. : raw_fd_ostream(getFD(Filename, EC, Flags), true) {}
  479. /// FD is the file descriptor that this writes to. If ShouldClose is true, this
  480. /// closes the file when the stream is destroyed.
  481. raw_fd_ostream::raw_fd_ostream(int fd, bool shouldClose, bool unbuffered)
  482. : raw_pwrite_stream(unbuffered), FD(fd), ShouldClose(shouldClose),
  483. Error(false), UseAtomicWrites(false) {
  484. if (FD < 0 ) {
  485. ShouldClose = false;
  486. return;
  487. }
  488. // Get the starting position.
  489. off_t loc = llvm::sys::fs::msf_lseek(FD, 0, SEEK_CUR); // HLSL Change - msf_lseek
  490. #ifdef LLVM_ON_WIN32
  491. // MSVCRT's _lseek(SEEK_CUR) doesn't return -1 for pipes.
  492. sys::fs::file_status Status;
  493. std::error_code EC = status(FD, Status);
  494. SupportsSeeking = !EC && Status.type() == sys::fs::file_type::regular_file;
  495. #else
  496. SupportsSeeking = loc != (off_t)-1;
  497. #endif
  498. if (!SupportsSeeking)
  499. pos = 0;
  500. else
  501. pos = static_cast<uint64_t>(loc);
  502. }
  503. raw_fd_ostream::~raw_fd_ostream() {
  504. if (FD >= 0) {
  505. flush();
  506. if (ShouldClose && sys::Process::SafelyCloseFileDescriptor(FD))
  507. error_detected();
  508. }
  509. #ifdef __MINGW32__
  510. // On mingw, global dtors should not call exit().
  511. // report_fatal_error() invokes exit(). We know report_fatal_error()
  512. // might not write messages to stderr when any errors were detected
  513. // on FD == 2.
  514. if (FD == 2) return;
  515. #endif
  516. // If there are any pending errors, report them now. Clients wishing
  517. // to avoid report_fatal_error calls should check for errors with
  518. // has_error() and clear the error flag with clear_error() before
  519. // destructing raw_ostream objects which may have errors.
  520. if (has_error())
  521. report_fatal_error("IO failure on output stream.", /*GenCrashDiag=*/false);
  522. }
  523. void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) {
  524. assert(FD >= 0 && "File already closed.");
  525. pos += Size;
  526. do {
  527. ssize_t ret;
  528. // Check whether we should attempt to use atomic writes.
  529. if (LLVM_LIKELY(!UseAtomicWrites)) {
  530. ret = llvm::sys::fs::msf_write(FD, Ptr, Size);
  531. } else {
  532. // Use ::writev() where available.
  533. #if defined(HAVE_WRITEV)
  534. const void *Addr = static_cast<const void *>(Ptr);
  535. struct iovec IOV = {const_cast<void *>(Addr), Size };
  536. ret = ::writev(FD, &IOV, 1);
  537. #else
  538. ret = llvm::sys::fs::msf_write(FD, Ptr, Size);
  539. #endif
  540. }
  541. if (ret < 0) {
  542. // If it's a recoverable error, swallow it and retry the write.
  543. //
  544. // Ideally we wouldn't ever see EAGAIN or EWOULDBLOCK here, since
  545. // raw_ostream isn't designed to do non-blocking I/O. However, some
  546. // programs, such as old versions of bjam, have mistakenly used
  547. // O_NONBLOCK. For compatibility, emulate blocking semantics by
  548. // spinning until the write succeeds. If you don't want spinning,
  549. // don't use O_NONBLOCK file descriptors with raw_ostream.
  550. if (errno == EINTR || errno == EAGAIN
  551. #ifdef EWOULDBLOCK
  552. || errno == EWOULDBLOCK
  553. #endif
  554. )
  555. continue;
  556. // Otherwise it's a non-recoverable error. Note it and quit.
  557. error_detected();
  558. break;
  559. }
  560. // The write may have written some or all of the data. Update the
  561. // size and buffer pointer to reflect the remainder that needs
  562. // to be written. If there are no bytes left, we're done.
  563. Ptr += ret;
  564. Size -= ret;
  565. } while (Size > 0);
  566. }
  567. void raw_fd_ostream::close() {
  568. assert(ShouldClose);
  569. ShouldClose = false;
  570. flush();
  571. if (sys::Process::SafelyCloseFileDescriptor(FD))
  572. error_detected();
  573. FD = -1;
  574. }
  575. uint64_t raw_fd_ostream::seek(uint64_t off) {
  576. flush();
  577. pos = llvm::sys::fs::msf_lseek(FD, off, SEEK_SET); // HLSL Change
  578. if (pos == (uint64_t)-1)
  579. error_detected();
  580. return pos;
  581. }
  582. void raw_fd_ostream::pwrite_impl(const char *Ptr, size_t Size,
  583. uint64_t Offset) {
  584. uint64_t Pos = tell();
  585. seek(Offset);
  586. write(Ptr, Size);
  587. seek(Pos);
  588. }
  589. size_t raw_fd_ostream::preferred_buffer_size() const {
  590. #if !defined(_MSC_VER) && !defined(__MINGW32__) && !defined(__minix)
  591. // Windows and Minix have no st_blksize.
  592. assert(FD >= 0 && "File not yet open!");
  593. struct stat statbuf;
  594. if (fstat(FD, &statbuf) != 0)
  595. return 0;
  596. // If this is a terminal, don't use buffering. Line buffering
  597. // would be a more traditional thing to do, but it's not worth
  598. // the complexity.
  599. if (S_ISCHR(statbuf.st_mode) && isatty(FD))
  600. return 0;
  601. // Return the preferred block size.
  602. return statbuf.st_blksize;
  603. #else
  604. return raw_ostream::preferred_buffer_size();
  605. #endif
  606. }
  607. raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold,
  608. bool bg) {
  609. if (sys::Process::ColorNeedsFlush())
  610. flush();
  611. const char *colorcode =
  612. (colors == SAVEDCOLOR) ? sys::Process::OutputBold(bg)
  613. : sys::Process::OutputColor(colors, bold, bg);
  614. if (colorcode) {
  615. size_t len = strlen(colorcode);
  616. write(colorcode, len);
  617. // don't account colors towards output characters
  618. pos -= len;
  619. }
  620. return *this;
  621. }
  622. raw_ostream &raw_fd_ostream::resetColor() {
  623. if (sys::Process::ColorNeedsFlush())
  624. flush();
  625. const char *colorcode = sys::Process::ResetColor();
  626. if (colorcode) {
  627. size_t len = strlen(colorcode);
  628. write(colorcode, len);
  629. // don't account colors towards output characters
  630. pos -= len;
  631. }
  632. return *this;
  633. }
  634. raw_ostream &raw_fd_ostream::reverseColor() {
  635. if (sys::Process::ColorNeedsFlush())
  636. flush();
  637. const char *colorcode = sys::Process::OutputReverse();
  638. if (colorcode) {
  639. size_t len = strlen(colorcode);
  640. write(colorcode, len);
  641. // don't account colors towards output characters
  642. pos -= len;
  643. }
  644. return *this;
  645. }
  646. bool raw_fd_ostream::is_displayed() const {
  647. return sys::Process::FileDescriptorIsDisplayed(FD);
  648. }
  649. bool raw_fd_ostream::has_colors() const {
  650. return sys::Process::FileDescriptorHasColors(FD);
  651. }
  652. //===----------------------------------------------------------------------===//
  653. // outs(), errs(), nulls()
  654. //===----------------------------------------------------------------------===//
  655. /// outs() - This returns a reference to a raw_ostream for standard output.
  656. /// Use it like: outs() << "foo" << "bar";
  657. raw_ostream &llvm::outs() {
  658. // Set buffer settings to model stdout behavior.
  659. // Delete the file descriptor when the program exits, forcing error
  660. // detection. If you don't want this behavior, don't use outs().
  661. std::error_code EC;
  662. static raw_fd_ostream S("-", EC, sys::fs::F_None);
  663. assert(!EC);
  664. return S;
  665. }
  666. /// errs() - This returns a reference to a raw_ostream for standard error.
  667. /// Use it like: errs() << "foo" << "bar";
  668. raw_ostream &llvm::errs() {
  669. // Set standard error to be unbuffered by default.
  670. static raw_fd_ostream S(STDERR_FILENO, false, true);
  671. return S;
  672. }
  673. /// nulls() - This returns a reference to a raw_ostream which discards output.
  674. raw_ostream &llvm::nulls() {
  675. static raw_null_ostream S;
  676. return S;
  677. }
  678. //===----------------------------------------------------------------------===//
  679. // raw_string_ostream
  680. //===----------------------------------------------------------------------===//
  681. raw_string_ostream::~raw_string_ostream() {
  682. #if 0 // HLSL Change Starts
  683. flush();
  684. #else
  685. // C++ and exception in destructors don't play nice. The proper pattern
  686. // here is to have the raw_string_ostream's owner flush before destruction
  687. // and take appropriate action, like throwing or returning an error value.
  688. try {
  689. flush();
  690. }
  691. catch (const std::bad_alloc &) {
  692. // Don't std::terminate()
  693. }
  694. #endif // HLSL Change Ends
  695. }
  696. void raw_string_ostream::write_impl(const char *Ptr, size_t Size) {
  697. OS.append(Ptr, Size);
  698. }
  699. //===----------------------------------------------------------------------===//
  700. // raw_svector_ostream
  701. //===----------------------------------------------------------------------===//
  702. // The raw_svector_ostream implementation uses the SmallVector itself as the
  703. // buffer for the raw_ostream. We guarantee that the raw_ostream buffer is
  704. // always pointing past the end of the vector, but within the vector
  705. // capacity. This allows raw_ostream to write directly into the correct place,
  706. // and we only need to set the vector size when the data is flushed.
  707. raw_svector_ostream::raw_svector_ostream(SmallVectorImpl<char> &O, unsigned)
  708. : OS(O) {}
  709. raw_svector_ostream::raw_svector_ostream(SmallVectorImpl<char> &O) : OS(O) {
  710. init();
  711. }
  712. void raw_svector_ostream::init() {
  713. // Set up the initial external buffer. We make sure that the buffer has at
  714. // least 128 bytes free; raw_ostream itself only requires 64, but we want to
  715. // make sure that we don't grow the buffer unnecessarily on destruction (when
  716. // the data is flushed). See the FIXME below.
  717. OS.reserve(OS.size() + 128);
  718. SetBuffer(OS.end(), OS.capacity() - OS.size());
  719. }
  720. raw_svector_ostream::~raw_svector_ostream() {
  721. // FIXME: Prevent resizing during this flush().
  722. flush();
  723. }
  724. void raw_svector_ostream::pwrite_impl(const char *Ptr, size_t Size,
  725. uint64_t Offset) {
  726. flush();
  727. memcpy(OS.begin() + Offset, Ptr, Size);
  728. }
  729. /// resync - This is called when the SmallVector we're appending to is changed
  730. /// outside of the raw_svector_ostream's control. It is only safe to do this
  731. /// if the raw_svector_ostream has previously been flushed.
  732. void raw_svector_ostream::resync() {
  733. assert(GetNumBytesInBuffer() == 0 && "Didn't flush before mutating vector");
  734. if (OS.capacity() - OS.size() < 64)
  735. OS.reserve(OS.capacity() * 2);
  736. SetBuffer(OS.end(), OS.capacity() - OS.size());
  737. }
  738. void raw_svector_ostream::write_impl(const char *Ptr, size_t Size) {
  739. if (Ptr == OS.end()) {
  740. // Grow the buffer to include the scratch area without copying.
  741. size_t NewSize = OS.size() + Size;
  742. assert(NewSize <= OS.capacity() && "Invalid write_impl() call!");
  743. OS.set_size(NewSize);
  744. } else {
  745. assert(!GetNumBytesInBuffer());
  746. OS.append(Ptr, Ptr + Size);
  747. }
  748. OS.reserve(OS.size() + 64);
  749. SetBuffer(OS.end(), OS.capacity() - OS.size());
  750. }
  751. uint64_t raw_svector_ostream::current_pos() const {
  752. return OS.size();
  753. }
  754. StringRef raw_svector_ostream::str() {
  755. flush();
  756. return StringRef(OS.begin(), OS.size());
  757. }
  758. //===----------------------------------------------------------------------===//
  759. // raw_null_ostream
  760. //===----------------------------------------------------------------------===//
  761. raw_null_ostream::~raw_null_ostream() {
  762. #ifndef NDEBUG
  763. // ~raw_ostream asserts that the buffer is empty. This isn't necessary
  764. // with raw_null_ostream, but it's better to have raw_null_ostream follow
  765. // the rules than to change the rules just for raw_null_ostream.
  766. flush();
  767. #endif
  768. }
  769. void raw_null_ostream::write_impl(const char *Ptr, size_t Size) {
  770. }
  771. uint64_t raw_null_ostream::current_pos() const {
  772. return 0;
  773. }
  774. void raw_null_ostream::pwrite_impl(const char *Ptr, size_t Size,
  775. uint64_t Offset) {}