raw_ostream.cpp 25 KB

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