stdio.cpp 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020, Sergey Bugaev <bugaevc@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/BuiltinWrappers.h>
  8. #include <AK/DeprecatedString.h>
  9. #include <AK/Format.h>
  10. #include <AK/PrintfImplementation.h>
  11. #include <AK/ScopedValueRollback.h>
  12. #include <AK/StdLibExtras.h>
  13. #include <LibC/bits/mutex_locker.h>
  14. #include <LibC/bits/stdio_file_implementation.h>
  15. #include <assert.h>
  16. #include <errno.h>
  17. #include <fcntl.h>
  18. #include <stdarg.h>
  19. #include <stdio.h>
  20. #include <stdio_ext.h>
  21. #include <stdlib.h>
  22. #include <string.h>
  23. #include <sys/internals.h>
  24. #include <sys/types.h>
  25. #include <sys/wait.h>
  26. #include <syscall.h>
  27. #include <unistd.h>
  28. static constinit pthread_mutex_t s_open_streams_lock = __PTHREAD_MUTEX_INITIALIZER;
  29. // The list of open files is initialized in __stdio_init.
  30. // We cannot rely on global constructors to initialize it, because it must
  31. // be initialized before other global constructors run. Similarly, we cannot
  32. // allow global destructors to destruct it.
  33. alignas(FILE::List) static u8 s_open_streams_storage[sizeof(FILE::List)];
  34. static FILE::List* const s_open_streams = reinterpret_cast<FILE::List*>(s_open_streams_storage);
  35. FILE::~FILE()
  36. {
  37. bool already_closed = m_fd == -1;
  38. VERIFY(already_closed);
  39. }
  40. FILE* FILE::create(int fd, int mode)
  41. {
  42. void* file_location = calloc(1, sizeof(FILE));
  43. if (file_location == nullptr)
  44. return nullptr;
  45. auto* file = new (file_location) FILE(fd, mode);
  46. LibC::MutexLocker locker(s_open_streams_lock);
  47. s_open_streams->append(*file);
  48. return file;
  49. }
  50. bool FILE::close()
  51. {
  52. bool flush_ok = flush();
  53. int rc = ::close(m_fd);
  54. m_fd = -1;
  55. if (!flush_ok) {
  56. // Restore the original error from flush().
  57. errno = m_error;
  58. }
  59. return flush_ok && rc == 0;
  60. }
  61. bool FILE::flush()
  62. {
  63. if (m_mode & O_WRONLY && m_buffer.may_use()) {
  64. // When open for writing, write out all the buffered data.
  65. while (m_buffer.is_not_empty()) {
  66. bool ok = write_from_buffer();
  67. if (!ok)
  68. return false;
  69. }
  70. }
  71. if (m_mode & O_RDONLY) {
  72. // When open for reading, just drop the buffered data.
  73. if constexpr (sizeof(size_t) >= sizeof(off_t))
  74. VERIFY(m_buffer.buffered_size() <= NumericLimits<off_t>::max());
  75. off_t had_buffered = static_cast<off_t>(m_buffer.buffered_size());
  76. m_buffer.drop();
  77. // Attempt to reset the underlying file position to what the user
  78. // expects.
  79. if (lseek(m_fd, -had_buffered, SEEK_CUR) < 0) {
  80. if (errno == ESPIPE) {
  81. // We can't set offset on this file; oh well, the user will just
  82. // have to cope.
  83. errno = 0;
  84. } else {
  85. return false;
  86. }
  87. }
  88. }
  89. return true;
  90. }
  91. void FILE::purge()
  92. {
  93. m_buffer.drop();
  94. }
  95. size_t FILE::pending()
  96. {
  97. if (m_mode & O_RDONLY) {
  98. return 0;
  99. }
  100. // FIXME: Check if our buffer is a write buffer, and only count those bytes.
  101. return m_buffer.buffered_size();
  102. }
  103. ssize_t FILE::do_read(u8* data, size_t size)
  104. {
  105. int nread = ::read(m_fd, data, size);
  106. if (nread < 0) {
  107. m_error = errno;
  108. } else if (nread == 0) {
  109. m_eof = true;
  110. }
  111. return nread;
  112. }
  113. ssize_t FILE::do_write(u8 const* data, size_t size)
  114. {
  115. int nwritten = ::write(m_fd, data, size);
  116. if (nwritten < 0)
  117. m_error = errno;
  118. return nwritten;
  119. }
  120. bool FILE::read_into_buffer()
  121. {
  122. m_buffer.realize(m_fd);
  123. size_t available_size;
  124. u8* data = m_buffer.begin_enqueue(available_size);
  125. // If we want to read, the buffer must have some space!
  126. VERIFY(available_size);
  127. ssize_t nread = do_read(data, available_size);
  128. if (nread <= 0)
  129. return false;
  130. m_buffer.did_enqueue(nread);
  131. return true;
  132. }
  133. bool FILE::write_from_buffer()
  134. {
  135. size_t size;
  136. u8 const* data = m_buffer.begin_dequeue(size);
  137. // If we want to write, the buffer must have something in it!
  138. VERIFY(size);
  139. ssize_t nwritten = do_write(data, size);
  140. if (nwritten < 0)
  141. return false;
  142. m_buffer.did_dequeue(nwritten);
  143. return true;
  144. }
  145. size_t FILE::read(u8* data, size_t size)
  146. {
  147. size_t total_read = 0;
  148. m_flags |= Flags::LastRead;
  149. m_flags &= ~Flags::LastWrite;
  150. while (size > 0) {
  151. size_t actual_size;
  152. if (m_buffer.may_use()) {
  153. // Let's see if the buffer has something queued for us.
  154. size_t queued_size;
  155. u8 const* queued_data = m_buffer.begin_dequeue(queued_size);
  156. if (queued_size == 0) {
  157. // Nothing buffered; we're going to have to read some.
  158. bool read_some_more = read_into_buffer();
  159. if (read_some_more) {
  160. // Great, now try this again.
  161. continue;
  162. }
  163. return total_read;
  164. }
  165. actual_size = min(size, queued_size);
  166. memcpy(data, queued_data, actual_size);
  167. m_buffer.did_dequeue(actual_size);
  168. } else {
  169. // Read directly into the user buffer.
  170. ssize_t nread = do_read(data, size);
  171. if (nread <= 0)
  172. return total_read;
  173. actual_size = nread;
  174. }
  175. total_read += actual_size;
  176. data += actual_size;
  177. size -= actual_size;
  178. }
  179. return total_read;
  180. }
  181. size_t FILE::write(u8 const* data, size_t size)
  182. {
  183. size_t total_written = 0;
  184. m_flags &= ~Flags::LastRead;
  185. m_flags |= Flags::LastWrite;
  186. while (size > 0) {
  187. size_t actual_size;
  188. if (m_buffer.may_use()) {
  189. m_buffer.realize(m_fd);
  190. // Try writing into the buffer.
  191. size_t available_size;
  192. u8* buffer_data = m_buffer.begin_enqueue(available_size);
  193. if (available_size == 0) {
  194. // There's no space in the buffer; we're going to free some.
  195. bool freed_some_space = write_from_buffer();
  196. if (freed_some_space) {
  197. // Great, now try this again.
  198. continue;
  199. }
  200. return total_written;
  201. }
  202. actual_size = min(size, available_size);
  203. memcpy(buffer_data, data, actual_size);
  204. m_buffer.did_enqueue(actual_size);
  205. // See if we have to flush it.
  206. if (m_buffer.mode() == _IOLBF) {
  207. bool includes_newline = memchr(data, '\n', actual_size);
  208. if (includes_newline)
  209. flush();
  210. }
  211. } else {
  212. // Write directly from the user buffer.
  213. ssize_t nwritten = do_write(data, size);
  214. if (nwritten < 0)
  215. return total_written;
  216. actual_size = nwritten;
  217. }
  218. total_written += actual_size;
  219. data += actual_size;
  220. size -= actual_size;
  221. }
  222. return total_written;
  223. }
  224. template<typename T>
  225. bool FILE::gets(T* data, size_t size)
  226. {
  227. // gets() is a lot like read(), but it is different enough in how it
  228. // processes newlines and null-terminates the buffer that it deserves a
  229. // separate implementation.
  230. size_t total_read = 0;
  231. if (size == 0)
  232. return false;
  233. m_flags |= Flags::LastRead;
  234. m_flags &= ~Flags::LastWrite;
  235. while (size > 1) {
  236. if (m_buffer.may_use()) {
  237. // Let's see if the buffer has something queued for us.
  238. size_t queued_size;
  239. T const* queued_data = bit_cast<T const*>(m_buffer.begin_dequeue(queued_size));
  240. queued_size /= sizeof(T);
  241. if (queued_size == 0) {
  242. // Nothing buffered; we're going to have to read some.
  243. bool read_some_more = read_into_buffer();
  244. if (read_some_more) {
  245. // Great, now try this again.
  246. continue;
  247. }
  248. *data = 0;
  249. return total_read > 0;
  250. }
  251. size_t actual_size = min(size - 1, queued_size);
  252. T const* newline = nullptr;
  253. for (size_t i = 0; i < actual_size; ++i) {
  254. if (queued_data[i] != '\n')
  255. continue;
  256. newline = &queued_data[i];
  257. actual_size = i + 1;
  258. break;
  259. }
  260. memcpy(data, queued_data, actual_size * sizeof(T));
  261. m_buffer.did_dequeue(actual_size * sizeof(T));
  262. total_read += actual_size;
  263. data += actual_size;
  264. size -= actual_size;
  265. if (newline)
  266. break;
  267. } else {
  268. // Sadly, we have to actually read these characters one by one.
  269. T value;
  270. ssize_t nread = do_read(bit_cast<u8*>(&value), sizeof(T));
  271. if (nread <= 0) {
  272. *data = 0;
  273. return total_read > 0;
  274. }
  275. VERIFY(nread == sizeof(T));
  276. *data = value;
  277. total_read++;
  278. data++;
  279. size--;
  280. if (value == '\n')
  281. break;
  282. }
  283. }
  284. *data = 0;
  285. return total_read > 0;
  286. }
  287. int FILE::seek(off_t offset, int whence)
  288. {
  289. bool ok = flush();
  290. if (!ok)
  291. return -1;
  292. off_t off = lseek(m_fd, offset, whence);
  293. if (off < 0) {
  294. // Note: do not set m_error.
  295. return off;
  296. }
  297. m_eof = false;
  298. return 0;
  299. }
  300. off_t FILE::tell()
  301. {
  302. bool ok = flush();
  303. if (!ok)
  304. return -1;
  305. return lseek(m_fd, 0, SEEK_CUR);
  306. }
  307. void FILE::reopen(int fd, int mode)
  308. {
  309. // Dr. POSIX says: "Failure to flush or close the file descriptor
  310. // successfully shall be ignored"
  311. // and so we ignore any failures these two might have.
  312. flush();
  313. close();
  314. // Just in case flush() and close() didn't drop the buffer.
  315. m_buffer.drop();
  316. m_fd = fd;
  317. m_mode = mode;
  318. m_error = 0;
  319. m_eof = false;
  320. }
  321. u8 const* FILE::readptr(size_t& available_size)
  322. {
  323. return m_buffer.begin_dequeue(available_size);
  324. }
  325. void FILE::readptr_increase(size_t increment)
  326. {
  327. m_buffer.did_dequeue(increment);
  328. }
  329. FILE::Buffer::~Buffer()
  330. {
  331. if (m_data_is_malloced)
  332. free(m_data);
  333. }
  334. bool FILE::Buffer::may_use() const
  335. {
  336. return m_ungotten != 0u || m_mode != _IONBF;
  337. }
  338. void FILE::Buffer::realize(int fd)
  339. {
  340. if (m_mode == -1)
  341. m_mode = isatty(fd) ? _IOLBF : _IOFBF;
  342. if (m_mode != _IONBF && m_data == nullptr) {
  343. m_data = reinterpret_cast<u8*>(malloc(m_capacity));
  344. m_data_is_malloced = true;
  345. }
  346. }
  347. void FILE::Buffer::setbuf(u8* data, int mode, size_t size)
  348. {
  349. drop();
  350. m_mode = mode;
  351. if (data != nullptr) {
  352. m_data = data;
  353. m_capacity = size;
  354. }
  355. }
  356. void FILE::Buffer::drop()
  357. {
  358. if (m_data_is_malloced) {
  359. free(m_data);
  360. m_data = nullptr;
  361. m_data_is_malloced = false;
  362. }
  363. m_begin = m_end = 0;
  364. m_empty = true;
  365. m_ungotten = 0u;
  366. }
  367. size_t FILE::Buffer::buffered_size() const
  368. {
  369. // Note: does not include the ungetc() buffer.
  370. if (m_empty)
  371. return 0;
  372. if (m_begin < m_end)
  373. return m_end - m_begin;
  374. else
  375. return m_capacity - (m_begin - m_end);
  376. }
  377. u8 const* FILE::Buffer::begin_dequeue(size_t& available_size) const
  378. {
  379. if (m_ungotten != 0u) {
  380. auto available_bytes = count_trailing_zeroes(m_ungotten) + 1;
  381. available_size = available_bytes;
  382. return &m_unget_buffer[unget_buffer_size - available_bytes];
  383. }
  384. if (m_empty) {
  385. available_size = 0;
  386. return nullptr;
  387. }
  388. if (m_begin < m_end)
  389. available_size = m_end - m_begin;
  390. else
  391. available_size = m_capacity - m_begin;
  392. return &m_data[m_begin];
  393. }
  394. void FILE::Buffer::did_dequeue(size_t actual_size)
  395. {
  396. VERIFY(actual_size > 0);
  397. if (m_ungotten != 0u) {
  398. VERIFY(actual_size <= static_cast<size_t>(popcount(m_ungotten & ungotten_mask)));
  399. auto available_bytes = count_trailing_zeroes(m_ungotten);
  400. m_ungotten &= (0xffffffffu << (actual_size + available_bytes));
  401. return;
  402. }
  403. m_begin += actual_size;
  404. VERIFY(m_begin <= m_capacity);
  405. if (m_begin == m_capacity) {
  406. // Wrap around.
  407. m_begin = 0;
  408. }
  409. if (m_begin == m_end) {
  410. m_empty = true;
  411. // As an optimization, move both pointers to the beginning of the
  412. // buffer, so that more consecutive space is available next time.
  413. m_begin = m_end = 0;
  414. }
  415. }
  416. u8* FILE::Buffer::begin_enqueue(size_t& available_size) const
  417. {
  418. VERIFY(m_data != nullptr);
  419. if (m_begin < m_end || m_empty)
  420. available_size = m_capacity - m_end;
  421. else
  422. available_size = m_begin - m_end;
  423. return const_cast<u8*>(&m_data[m_end]);
  424. }
  425. void FILE::Buffer::did_enqueue(size_t actual_size)
  426. {
  427. VERIFY(m_data != nullptr);
  428. VERIFY(actual_size > 0);
  429. m_end += actual_size;
  430. VERIFY(m_end <= m_capacity);
  431. if (m_end == m_capacity) {
  432. // Wrap around.
  433. m_end = 0;
  434. }
  435. m_empty = false;
  436. }
  437. bool FILE::Buffer::enqueue_front(u8 byte)
  438. {
  439. size_t placement_index;
  440. if (m_ungotten == 0u) {
  441. placement_index = 3u;
  442. m_ungotten = 1u;
  443. } else {
  444. auto first_zero_index = count_trailing_zeroes(bit_cast<u32>(~m_ungotten)); // Thanks C.
  445. if (first_zero_index >= unget_buffer_size) {
  446. // Sorry, the place is already taken!
  447. return false;
  448. }
  449. placement_index = unget_buffer_size - first_zero_index - 1;
  450. m_ungotten |= (1 << first_zero_index);
  451. }
  452. m_unget_buffer[placement_index] = byte;
  453. return true;
  454. }
  455. void FILE::lock()
  456. {
  457. pthread_mutex_lock(&m_mutex);
  458. }
  459. void FILE::unlock()
  460. {
  461. pthread_mutex_unlock(&m_mutex);
  462. }
  463. extern "C" {
  464. alignas(FILE) static u8 default_streams[3][sizeof(FILE)];
  465. FILE* stdin = reinterpret_cast<FILE*>(&default_streams[0]);
  466. FILE* stdout = reinterpret_cast<FILE*>(&default_streams[1]);
  467. FILE* stderr = reinterpret_cast<FILE*>(&default_streams[2]);
  468. void __stdio_init()
  469. {
  470. new (s_open_streams) FILE::List();
  471. new (stdin) FILE(0, O_RDONLY);
  472. new (stdout) FILE(1, O_WRONLY);
  473. new (stderr) FILE(2, O_WRONLY);
  474. stderr->setbuf(nullptr, _IONBF, 0);
  475. s_open_streams->append(*stdin);
  476. s_open_streams->append(*stdout);
  477. s_open_streams->append(*stderr);
  478. __stdio_is_initialized = true;
  479. }
  480. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/setvbuf.html
  481. int setvbuf(FILE* stream, char* buf, int mode, size_t size)
  482. {
  483. VERIFY(stream);
  484. ScopedFileLock lock(stream);
  485. if (mode != _IONBF && mode != _IOLBF && mode != _IOFBF) {
  486. errno = EINVAL;
  487. return -1;
  488. }
  489. stream->setbuf(reinterpret_cast<u8*>(buf), mode, size);
  490. return 0;
  491. }
  492. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/setbuf.html
  493. void setbuf(FILE* stream, char* buf)
  494. {
  495. setvbuf(stream, buf, buf ? _IOFBF : _IONBF, BUFSIZ);
  496. }
  497. void setlinebuf(FILE* stream)
  498. {
  499. setvbuf(stream, nullptr, _IOLBF, 0);
  500. }
  501. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/fileno.html
  502. int fileno(FILE* stream)
  503. {
  504. VERIFY(stream);
  505. ScopedFileLock lock(stream);
  506. return stream->fileno();
  507. }
  508. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/feof.html
  509. int feof(FILE* stream)
  510. {
  511. VERIFY(stream);
  512. ScopedFileLock lock(stream);
  513. return stream->eof();
  514. }
  515. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/fflush.html
  516. int fflush(FILE* stream)
  517. {
  518. if (!stream) {
  519. int rc = 0;
  520. LibC::MutexLocker locker(s_open_streams_lock);
  521. for (auto& file : *s_open_streams) {
  522. ScopedFileLock lock(&file);
  523. rc = file.flush() ? rc : EOF;
  524. }
  525. return rc;
  526. }
  527. ScopedFileLock lock(stream);
  528. return stream->flush() ? 0 : EOF;
  529. }
  530. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/fgets.html
  531. char* fgets(char* buffer, int size, FILE* stream)
  532. {
  533. VERIFY(stream);
  534. ScopedFileLock lock(stream);
  535. bool ok = stream->gets(reinterpret_cast<u8*>(buffer), size);
  536. return ok ? buffer : nullptr;
  537. }
  538. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/fgetc.html
  539. int fgetc(FILE* stream)
  540. {
  541. VERIFY(stream);
  542. unsigned char ch;
  543. size_t nread = fread(&ch, sizeof(unsigned char), 1, stream);
  544. if (nread == 1) {
  545. return ch;
  546. }
  547. return EOF;
  548. }
  549. int fgetc_unlocked(FILE* stream)
  550. {
  551. VERIFY(stream);
  552. unsigned char ch;
  553. size_t nread = fread_unlocked(&ch, sizeof(unsigned char), 1, stream);
  554. if (nread == 1)
  555. return ch;
  556. return EOF;
  557. }
  558. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/getc.html
  559. int getc(FILE* stream)
  560. {
  561. return fgetc(stream);
  562. }
  563. int getc_unlocked(FILE* stream)
  564. {
  565. return fgetc_unlocked(stream);
  566. }
  567. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/getchar.html
  568. int getchar()
  569. {
  570. return getc(stdin);
  571. }
  572. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/getdelim.html
  573. ssize_t getdelim(char** lineptr, size_t* n, int delim, FILE* stream)
  574. {
  575. if (!lineptr || !n) {
  576. errno = EINVAL;
  577. return -1;
  578. }
  579. if (*lineptr == nullptr || *n == 0) {
  580. *n = BUFSIZ;
  581. if ((*lineptr = static_cast<char*>(malloc(*n))) == nullptr) {
  582. return -1;
  583. }
  584. }
  585. char* ptr;
  586. char* eptr;
  587. for (ptr = *lineptr, eptr = *lineptr + *n;;) {
  588. int c = fgetc(stream);
  589. if (c == -1) {
  590. if (feof(stream)) {
  591. *ptr = '\0';
  592. return ptr == *lineptr ? -1 : ptr - *lineptr;
  593. } else {
  594. return -1;
  595. }
  596. }
  597. *ptr++ = c;
  598. if (c == delim) {
  599. *ptr = '\0';
  600. return ptr - *lineptr;
  601. }
  602. if (ptr + 2 >= eptr) {
  603. char* nbuf;
  604. size_t nbuf_sz = *n * 2;
  605. ssize_t d = ptr - *lineptr;
  606. if ((nbuf = static_cast<char*>(realloc(*lineptr, nbuf_sz))) == nullptr) {
  607. return -1;
  608. }
  609. *lineptr = nbuf;
  610. *n = nbuf_sz;
  611. eptr = nbuf + nbuf_sz;
  612. ptr = nbuf + d;
  613. }
  614. }
  615. }
  616. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/getline.html
  617. ssize_t getline(char** lineptr, size_t* n, FILE* stream)
  618. {
  619. return getdelim(lineptr, n, '\n', stream);
  620. }
  621. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/ungetc.html
  622. int ungetc(int c, FILE* stream)
  623. {
  624. VERIFY(stream);
  625. ScopedFileLock lock(stream);
  626. bool ok = stream->ungetc(c);
  627. return ok ? c : EOF;
  628. }
  629. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/fputc.html
  630. int fputc(int ch, FILE* stream)
  631. {
  632. VERIFY(stream);
  633. u8 byte = ch;
  634. ScopedFileLock lock(stream);
  635. size_t nwritten = stream->write(&byte, 1);
  636. if (nwritten == 0)
  637. return EOF;
  638. VERIFY(nwritten == 1);
  639. return byte;
  640. }
  641. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/putc.html
  642. int putc(int ch, FILE* stream)
  643. {
  644. return fputc(ch, stream);
  645. }
  646. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/putchar.html
  647. int putchar(int ch)
  648. {
  649. return putc(ch, stdout);
  650. }
  651. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/fputs.html
  652. int fputs(char const* s, FILE* stream)
  653. {
  654. VERIFY(stream);
  655. size_t len = strlen(s);
  656. ScopedFileLock lock(stream);
  657. size_t nwritten = stream->write(reinterpret_cast<u8 const*>(s), len);
  658. if (nwritten < len)
  659. return EOF;
  660. return 1;
  661. }
  662. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/puts.html
  663. int puts(char const* s)
  664. {
  665. int rc = fputs(s, stdout);
  666. if (rc == EOF)
  667. return EOF;
  668. return fputc('\n', stdout);
  669. }
  670. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/clearerr.html
  671. void clearerr(FILE* stream)
  672. {
  673. VERIFY(stream);
  674. ScopedFileLock lock(stream);
  675. stream->clear_err();
  676. }
  677. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/ferror.html
  678. int ferror(FILE* stream)
  679. {
  680. VERIFY(stream);
  681. ScopedFileLock lock(stream);
  682. return stream->error();
  683. }
  684. size_t fread_unlocked(void* ptr, size_t size, size_t nmemb, FILE* stream)
  685. {
  686. VERIFY(stream);
  687. VERIFY(!Checked<size_t>::multiplication_would_overflow(size, nmemb));
  688. size_t nread = stream->read(reinterpret_cast<u8*>(ptr), size * nmemb);
  689. if (!nread)
  690. return 0;
  691. return nread / size;
  692. }
  693. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/fread.html
  694. size_t fread(void* ptr, size_t size, size_t nmemb, FILE* stream)
  695. {
  696. VERIFY(stream);
  697. ScopedFileLock lock(stream);
  698. return fread_unlocked(ptr, size, nmemb, stream);
  699. }
  700. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/fwrite.html
  701. size_t fwrite(void const* ptr, size_t size, size_t nmemb, FILE* stream)
  702. {
  703. VERIFY(stream);
  704. VERIFY(!Checked<size_t>::multiplication_would_overflow(size, nmemb));
  705. ScopedFileLock lock(stream);
  706. size_t nwritten = stream->write(reinterpret_cast<u8 const*>(ptr), size * nmemb);
  707. if (!nwritten)
  708. return 0;
  709. return nwritten / size;
  710. }
  711. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/fseek.html
  712. int fseek(FILE* stream, long offset, int whence)
  713. {
  714. VERIFY(stream);
  715. ScopedFileLock lock(stream);
  716. return stream->seek(offset, whence);
  717. }
  718. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/fseeko.html
  719. int fseeko(FILE* stream, off_t offset, int whence)
  720. {
  721. VERIFY(stream);
  722. ScopedFileLock lock(stream);
  723. return stream->seek(offset, whence);
  724. }
  725. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/ftell.html
  726. long ftell(FILE* stream)
  727. {
  728. VERIFY(stream);
  729. ScopedFileLock lock(stream);
  730. return stream->tell();
  731. }
  732. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/ftello.html
  733. off_t ftello(FILE* stream)
  734. {
  735. VERIFY(stream);
  736. ScopedFileLock lock(stream);
  737. return stream->tell();
  738. }
  739. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/fgetpos.html
  740. int fgetpos(FILE* stream, fpos_t* pos)
  741. {
  742. VERIFY(stream);
  743. VERIFY(pos);
  744. ScopedFileLock lock(stream);
  745. off_t val = stream->tell();
  746. if (val == -1L)
  747. return 1;
  748. *pos = val;
  749. return 0;
  750. }
  751. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/fsetpos.html
  752. int fsetpos(FILE* stream, fpos_t const* pos)
  753. {
  754. VERIFY(stream);
  755. VERIFY(pos);
  756. ScopedFileLock lock(stream);
  757. return stream->seek(*pos, SEEK_SET);
  758. }
  759. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/rewind.html
  760. void rewind(FILE* stream)
  761. {
  762. fseek(stream, 0, SEEK_SET);
  763. clearerr(stream);
  764. }
  765. ALWAYS_INLINE void stdout_putch(char*&, char ch)
  766. {
  767. putchar(ch);
  768. }
  769. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/vfprintf.html
  770. int vfprintf(FILE* stream, char const* fmt, va_list ap)
  771. {
  772. return printf_internal([stream](auto, char ch) { fputc(ch, stream); }, nullptr, fmt, ap);
  773. }
  774. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/fprintf.html
  775. int fprintf(FILE* stream, char const* fmt, ...)
  776. {
  777. va_list ap;
  778. va_start(ap, fmt);
  779. int ret = vfprintf(stream, fmt, ap);
  780. va_end(ap);
  781. return ret;
  782. }
  783. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/vprintf.html
  784. int vprintf(char const* fmt, va_list ap)
  785. {
  786. return printf_internal(stdout_putch, nullptr, fmt, ap);
  787. }
  788. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/printf.html
  789. int printf(char const* fmt, ...)
  790. {
  791. va_list ap;
  792. va_start(ap, fmt);
  793. int ret = vprintf(fmt, ap);
  794. va_end(ap);
  795. return ret;
  796. }
  797. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/vasprintf.html
  798. int vasprintf(char** strp, char const* fmt, va_list ap)
  799. {
  800. StringBuilder builder;
  801. builder.appendvf(fmt, ap);
  802. VERIFY(builder.length() <= NumericLimits<int>::max());
  803. int length = builder.length();
  804. *strp = strdup(builder.to_deprecated_string().characters());
  805. return length;
  806. }
  807. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/asprintf.html
  808. int asprintf(char** strp, char const* fmt, ...)
  809. {
  810. StringBuilder builder;
  811. va_list ap;
  812. va_start(ap, fmt);
  813. builder.appendvf(fmt, ap);
  814. va_end(ap);
  815. VERIFY(builder.length() <= NumericLimits<int>::max());
  816. int length = builder.length();
  817. *strp = strdup(builder.to_deprecated_string().characters());
  818. return length;
  819. }
  820. static void buffer_putch(char*& bufptr, char ch)
  821. {
  822. *bufptr++ = ch;
  823. }
  824. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/vsprintf.html
  825. int vsprintf(char* buffer, char const* fmt, va_list ap)
  826. {
  827. int ret = printf_internal(buffer_putch, buffer, fmt, ap);
  828. buffer[ret] = '\0';
  829. return ret;
  830. }
  831. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/sprintf.html
  832. int sprintf(char* buffer, char const* fmt, ...)
  833. {
  834. va_list ap;
  835. va_start(ap, fmt);
  836. int ret = vsprintf(buffer, fmt, ap);
  837. va_end(ap);
  838. return ret;
  839. }
  840. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/vsnprintf.html
  841. int vsnprintf(char* buffer, size_t size, char const* fmt, va_list ap)
  842. {
  843. size_t space_remaining = 0;
  844. if (size) {
  845. space_remaining = size - 1;
  846. } else {
  847. space_remaining = 0;
  848. }
  849. auto sized_buffer_putch = [&](char*& bufptr, char ch) {
  850. if (space_remaining) {
  851. *bufptr++ = ch;
  852. --space_remaining;
  853. }
  854. };
  855. int ret = printf_internal(sized_buffer_putch, buffer, fmt, ap);
  856. if (space_remaining) {
  857. buffer[ret] = '\0';
  858. } else if (size > 0) {
  859. buffer[size - 1] = '\0';
  860. }
  861. return ret;
  862. }
  863. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/snprintf.html
  864. int snprintf(char* buffer, size_t size, char const* fmt, ...)
  865. {
  866. va_list ap;
  867. va_start(ap, fmt);
  868. int ret = vsnprintf(buffer, size, fmt, ap);
  869. va_end(ap);
  870. return ret;
  871. }
  872. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/perror.html
  873. void perror(char const* s)
  874. {
  875. int saved_errno = errno;
  876. dbgln("perror(): {}: {}", s, strerror(saved_errno));
  877. warnln("{}: {}", s, strerror(saved_errno));
  878. }
  879. static int parse_mode(char const* mode)
  880. {
  881. int flags = 0;
  882. // NOTE: rt is a non-standard mode which opens a file for read, explicitly
  883. // specifying that it's a text file
  884. for (auto* ptr = mode; *ptr; ++ptr) {
  885. switch (*ptr) {
  886. case 'r':
  887. flags |= O_RDONLY;
  888. break;
  889. case 'w':
  890. flags |= O_WRONLY | O_CREAT | O_TRUNC;
  891. break;
  892. case 'a':
  893. flags |= O_WRONLY | O_APPEND | O_CREAT;
  894. break;
  895. case '+':
  896. flags |= O_RDWR;
  897. break;
  898. case 'e':
  899. flags |= O_CLOEXEC;
  900. break;
  901. case 'b':
  902. // Ok...
  903. break;
  904. case 't':
  905. // Ok...
  906. break;
  907. default:
  908. dbgln("Potentially unsupported fopen mode _{}_ (because of '{}')", mode, *ptr);
  909. }
  910. }
  911. return flags;
  912. }
  913. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/fopen.html
  914. FILE* fopen(char const* pathname, char const* mode)
  915. {
  916. int flags = parse_mode(mode);
  917. int fd = open(pathname, flags, 0666);
  918. if (fd < 0)
  919. return nullptr;
  920. return FILE::create(fd, flags);
  921. }
  922. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/freopen.html
  923. FILE* freopen(char const* pathname, char const* mode, FILE* stream)
  924. {
  925. VERIFY(stream);
  926. if (!pathname) {
  927. // FIXME: Someone should probably implement this path.
  928. TODO();
  929. }
  930. int flags = parse_mode(mode);
  931. int fd = open(pathname, flags, 0666);
  932. if (fd < 0)
  933. return nullptr;
  934. stream->reopen(fd, flags);
  935. return stream;
  936. }
  937. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/fdopen.html
  938. FILE* fdopen(int fd, char const* mode)
  939. {
  940. int flags = parse_mode(mode);
  941. // FIXME: Verify that the mode matches how fd is already open.
  942. if (fd < 0)
  943. return nullptr;
  944. return FILE::create(fd, flags);
  945. }
  946. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/fmemopen.html
  947. FILE* fmemopen(void*, size_t, char const*)
  948. {
  949. // FIXME: Implement me :^)
  950. TODO();
  951. }
  952. static inline bool is_default_stream(FILE* stream)
  953. {
  954. return stream == stdin || stream == stdout || stream == stderr;
  955. }
  956. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/fclose.html
  957. int fclose(FILE* stream)
  958. {
  959. VERIFY(stream);
  960. bool ok;
  961. {
  962. ScopedFileLock lock(stream);
  963. ok = stream->close();
  964. }
  965. ScopedValueRollback errno_restorer(errno);
  966. {
  967. LibC::MutexLocker locker(s_open_streams_lock);
  968. s_open_streams->remove(*stream);
  969. }
  970. stream->~FILE();
  971. if (!is_default_stream(stream))
  972. free(stream);
  973. return ok ? 0 : EOF;
  974. }
  975. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/rename.html
  976. int rename(char const* oldpath, char const* newpath)
  977. {
  978. return renameat(AT_FDCWD, oldpath, AT_FDCWD, newpath);
  979. }
  980. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/renameat.html
  981. int renameat(int olddirfd, char const* oldpath, int newdirfd, char const* newpath)
  982. {
  983. if (!oldpath || !newpath) {
  984. errno = EFAULT;
  985. return -1;
  986. }
  987. Syscall::SC_rename_params params { olddirfd, { oldpath, strlen(oldpath) }, newdirfd, { newpath, strlen(newpath) } };
  988. int rc = syscall(SC_rename, &params);
  989. __RETURN_WITH_ERRNO(rc, rc, -1);
  990. }
  991. void dbgputstr(char const* characters, size_t length)
  992. {
  993. syscall(SC_dbgputstr, characters, length);
  994. }
  995. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/tmpnam.html
  996. char* tmpnam(char*)
  997. {
  998. dbgln("FIXME: Implement tmpnam()");
  999. TODO();
  1000. }
  1001. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/popen.html
  1002. FILE* popen(char const* command, char const* type)
  1003. {
  1004. if (!type || (*type != 'r' && *type != 'w')) {
  1005. errno = EINVAL;
  1006. return nullptr;
  1007. }
  1008. int pipe_fds[2];
  1009. if (pipe(pipe_fds) < 0) {
  1010. ScopedValueRollback rollback(errno);
  1011. perror("pipe");
  1012. return nullptr;
  1013. }
  1014. pid_t child_pid = fork();
  1015. if (child_pid < 0) {
  1016. ScopedValueRollback rollback(errno);
  1017. perror("fork");
  1018. close(pipe_fds[0]);
  1019. close(pipe_fds[1]);
  1020. return nullptr;
  1021. } else if (child_pid == 0) {
  1022. if (*type == 'r') {
  1023. if (dup2(pipe_fds[1], STDOUT_FILENO) < 0) {
  1024. perror("dup2");
  1025. exit(1);
  1026. }
  1027. close(pipe_fds[0]);
  1028. close(pipe_fds[1]);
  1029. } else if (*type == 'w') {
  1030. if (dup2(pipe_fds[0], STDIN_FILENO) < 0) {
  1031. perror("dup2");
  1032. exit(1);
  1033. }
  1034. close(pipe_fds[0]);
  1035. close(pipe_fds[1]);
  1036. }
  1037. if (execl("/bin/sh", "sh", "-c", command, nullptr) < 0)
  1038. perror("execl");
  1039. exit(1);
  1040. }
  1041. FILE* file = nullptr;
  1042. if (*type == 'r') {
  1043. file = FILE::create(pipe_fds[0], O_RDONLY);
  1044. close(pipe_fds[1]);
  1045. } else if (*type == 'w') {
  1046. file = FILE::create(pipe_fds[1], O_WRONLY);
  1047. close(pipe_fds[0]);
  1048. }
  1049. file->set_popen_child(child_pid);
  1050. return file;
  1051. }
  1052. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/pclose.html
  1053. int pclose(FILE* stream)
  1054. {
  1055. VERIFY(stream);
  1056. VERIFY(stream->popen_child() != 0);
  1057. int wstatus = 0;
  1058. if (waitpid(stream->popen_child(), &wstatus, 0) < 0)
  1059. return -1;
  1060. return wstatus;
  1061. }
  1062. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/remove.html
  1063. int remove(char const* pathname)
  1064. {
  1065. if (unlink(pathname) < 0) {
  1066. if (errno == EISDIR)
  1067. return rmdir(pathname);
  1068. return -1;
  1069. }
  1070. return 0;
  1071. }
  1072. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/scanf.html
  1073. int scanf(char const* fmt, ...)
  1074. {
  1075. va_list ap;
  1076. va_start(ap, fmt);
  1077. int count = vfscanf(stdin, fmt, ap);
  1078. va_end(ap);
  1079. return count;
  1080. }
  1081. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/fscanf.html
  1082. int fscanf(FILE* stream, char const* fmt, ...)
  1083. {
  1084. va_list ap;
  1085. va_start(ap, fmt);
  1086. int count = vfscanf(stream, fmt, ap);
  1087. va_end(ap);
  1088. return count;
  1089. }
  1090. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/sscanf.html
  1091. int sscanf(char const* buffer, char const* fmt, ...)
  1092. {
  1093. va_list ap;
  1094. va_start(ap, fmt);
  1095. int count = vsscanf(buffer, fmt, ap);
  1096. va_end(ap);
  1097. return count;
  1098. }
  1099. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/vfscanf.html
  1100. int vfscanf(FILE* stream, char const* fmt, va_list ap)
  1101. {
  1102. char buffer[BUFSIZ];
  1103. if (!fgets(buffer, sizeof(buffer) - 1, stream))
  1104. return -1;
  1105. return vsscanf(buffer, fmt, ap);
  1106. }
  1107. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/vscanf.html
  1108. int vscanf(char const* fmt, va_list ap)
  1109. {
  1110. return vfscanf(stdin, fmt, ap);
  1111. }
  1112. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/flockfile.html
  1113. void flockfile(FILE* filehandle)
  1114. {
  1115. VERIFY(filehandle);
  1116. filehandle->lock();
  1117. }
  1118. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/funlockfile.html
  1119. void funlockfile(FILE* filehandle)
  1120. {
  1121. VERIFY(filehandle);
  1122. filehandle->unlock();
  1123. }
  1124. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/tmpfile.html
  1125. FILE* tmpfile()
  1126. {
  1127. char tmp_path[] = "/tmp/XXXXXX";
  1128. int fd = mkstemp(tmp_path);
  1129. if (fd < 0)
  1130. return nullptr;
  1131. // FIXME: instead of using this hack, implement with O_TMPFILE or similar
  1132. unlink(tmp_path);
  1133. return fdopen(fd, "rw");
  1134. }
  1135. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/ctermid.html
  1136. char* ctermid(char* s)
  1137. {
  1138. static char tty_path[L_ctermid] = "/dev/tty";
  1139. if (s)
  1140. return strcpy(s, tty_path);
  1141. return tty_path;
  1142. }
  1143. size_t __fpending(FILE* stream)
  1144. {
  1145. ScopedFileLock lock(stream);
  1146. return stream->pending();
  1147. }
  1148. int __freading(FILE* stream)
  1149. {
  1150. ScopedFileLock lock(stream);
  1151. if ((stream->mode() & O_RDWR) == O_RDONLY) {
  1152. return 1;
  1153. }
  1154. return (stream->flags() & FILE::Flags::LastRead);
  1155. }
  1156. int __fwriting(FILE* stream)
  1157. {
  1158. ScopedFileLock lock(stream);
  1159. if ((stream->mode() & O_RDWR) == O_WRONLY) {
  1160. return 1;
  1161. }
  1162. return (stream->flags() & FILE::Flags::LastWrite);
  1163. }
  1164. void __fpurge(FILE* stream)
  1165. {
  1166. ScopedFileLock lock(stream);
  1167. stream->purge();
  1168. }
  1169. size_t __freadahead(FILE* stream)
  1170. {
  1171. VERIFY(stream);
  1172. ScopedFileLock lock(stream);
  1173. size_t available_size;
  1174. stream->readptr(available_size);
  1175. return available_size;
  1176. }
  1177. char const* __freadptr(FILE* stream, size_t* sizep)
  1178. {
  1179. VERIFY(stream);
  1180. VERIFY(sizep);
  1181. ScopedFileLock lock(stream);
  1182. size_t available_size;
  1183. u8 const* ptr = stream->readptr(available_size);
  1184. if (available_size == 0)
  1185. return nullptr;
  1186. *sizep = available_size;
  1187. return reinterpret_cast<char const*>(ptr);
  1188. }
  1189. void __freadptrinc(FILE* stream, size_t increment)
  1190. {
  1191. VERIFY(stream);
  1192. ScopedFileLock lock(stream);
  1193. stream->readptr_increase(increment);
  1194. }
  1195. void __fseterr(FILE* stream)
  1196. {
  1197. ScopedFileLock lock(stream);
  1198. stream->set_err();
  1199. }
  1200. }
  1201. template bool FILE::gets<u8>(u8*, size_t);
  1202. template bool FILE::gets<u32>(u32*, size_t);