stdio.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350
  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/Format.h>
  9. #include <AK/PrintfImplementation.h>
  10. #include <AK/ScopedValueRollback.h>
  11. #include <AK/StdLibExtras.h>
  12. #include <AK/String.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. const T* queued_data = bit_cast<const T*>(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. FILE::Buffer::~Buffer()
  326. {
  327. if (m_data_is_malloced)
  328. free(m_data);
  329. }
  330. bool FILE::Buffer::may_use() const
  331. {
  332. return m_ungotten != 0u || m_mode != _IONBF;
  333. }
  334. void FILE::Buffer::realize(int fd)
  335. {
  336. if (m_mode == -1)
  337. m_mode = isatty(fd) ? _IOLBF : _IOFBF;
  338. if (m_mode != _IONBF && m_data == nullptr) {
  339. m_data = reinterpret_cast<u8*>(malloc(m_capacity));
  340. m_data_is_malloced = true;
  341. }
  342. }
  343. void FILE::Buffer::setbuf(u8* data, int mode, size_t size)
  344. {
  345. drop();
  346. m_mode = mode;
  347. if (data != nullptr) {
  348. m_data = data;
  349. m_capacity = size;
  350. }
  351. }
  352. void FILE::Buffer::drop()
  353. {
  354. if (m_data_is_malloced) {
  355. free(m_data);
  356. m_data = nullptr;
  357. m_data_is_malloced = false;
  358. }
  359. m_begin = m_end = 0;
  360. m_empty = true;
  361. m_ungotten = 0u;
  362. }
  363. size_t FILE::Buffer::buffered_size() const
  364. {
  365. // Note: does not include the ungetc() buffer.
  366. if (m_empty)
  367. return 0;
  368. if (m_begin < m_end)
  369. return m_end - m_begin;
  370. else
  371. return m_capacity - (m_begin - m_end);
  372. }
  373. u8 const* FILE::Buffer::begin_dequeue(size_t& available_size) const
  374. {
  375. if (m_ungotten != 0u) {
  376. auto available_bytes = count_trailing_zeroes(m_ungotten) + 1;
  377. available_size = available_bytes;
  378. return &m_unget_buffer[unget_buffer_size - available_bytes];
  379. }
  380. if (m_empty) {
  381. available_size = 0;
  382. return nullptr;
  383. }
  384. if (m_begin < m_end)
  385. available_size = m_end - m_begin;
  386. else
  387. available_size = m_capacity - m_begin;
  388. return &m_data[m_begin];
  389. }
  390. void FILE::Buffer::did_dequeue(size_t actual_size)
  391. {
  392. VERIFY(actual_size > 0);
  393. if (m_ungotten != 0u) {
  394. VERIFY(actual_size <= static_cast<size_t>(popcount(m_ungotten & ungotten_mask)));
  395. auto available_bytes = count_trailing_zeroes(m_ungotten);
  396. m_ungotten &= (0xffffffffu << (actual_size + available_bytes));
  397. return;
  398. }
  399. m_begin += actual_size;
  400. VERIFY(m_begin <= m_capacity);
  401. if (m_begin == m_capacity) {
  402. // Wrap around.
  403. m_begin = 0;
  404. }
  405. if (m_begin == m_end) {
  406. m_empty = true;
  407. // As an optimization, move both pointers to the beginning of the
  408. // buffer, so that more consecutive space is available next time.
  409. m_begin = m_end = 0;
  410. }
  411. }
  412. u8* FILE::Buffer::begin_enqueue(size_t& available_size) const
  413. {
  414. VERIFY(m_data != nullptr);
  415. if (m_begin < m_end || m_empty)
  416. available_size = m_capacity - m_end;
  417. else
  418. available_size = m_begin - m_end;
  419. return const_cast<u8*>(&m_data[m_end]);
  420. }
  421. void FILE::Buffer::did_enqueue(size_t actual_size)
  422. {
  423. VERIFY(m_data != nullptr);
  424. VERIFY(actual_size > 0);
  425. m_end += actual_size;
  426. VERIFY(m_end <= m_capacity);
  427. if (m_end == m_capacity) {
  428. // Wrap around.
  429. m_end = 0;
  430. }
  431. m_empty = false;
  432. }
  433. bool FILE::Buffer::enqueue_front(u8 byte)
  434. {
  435. size_t placement_index;
  436. if (m_ungotten == 0u) {
  437. placement_index = 3u;
  438. m_ungotten = 1u;
  439. } else {
  440. auto first_zero_index = count_trailing_zeroes(bit_cast<u32>(~m_ungotten)); // Thanks C.
  441. if (first_zero_index >= unget_buffer_size) {
  442. // Sorry, the place is already taken!
  443. return false;
  444. }
  445. placement_index = unget_buffer_size - first_zero_index - 1;
  446. m_ungotten |= (1 << first_zero_index);
  447. }
  448. m_unget_buffer[placement_index] = byte;
  449. return true;
  450. }
  451. void FILE::lock()
  452. {
  453. __pthread_mutex_lock(&m_mutex);
  454. }
  455. void FILE::unlock()
  456. {
  457. __pthread_mutex_unlock(&m_mutex);
  458. }
  459. extern "C" {
  460. alignas(FILE) static u8 default_streams[3][sizeof(FILE)];
  461. FILE* stdin = reinterpret_cast<FILE*>(&default_streams[0]);
  462. FILE* stdout = reinterpret_cast<FILE*>(&default_streams[1]);
  463. FILE* stderr = reinterpret_cast<FILE*>(&default_streams[2]);
  464. void __stdio_init()
  465. {
  466. new (s_open_streams) FILE::List();
  467. new (stdin) FILE(0, O_RDONLY);
  468. new (stdout) FILE(1, O_WRONLY);
  469. new (stderr) FILE(2, O_WRONLY);
  470. stderr->setbuf(nullptr, _IONBF, 0);
  471. s_open_streams->append(*stdin);
  472. s_open_streams->append(*stdout);
  473. s_open_streams->append(*stderr);
  474. __stdio_is_initialized = true;
  475. }
  476. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/setvbuf.html
  477. int setvbuf(FILE* stream, char* buf, int mode, size_t size)
  478. {
  479. VERIFY(stream);
  480. ScopedFileLock lock(stream);
  481. if (mode != _IONBF && mode != _IOLBF && mode != _IOFBF) {
  482. errno = EINVAL;
  483. return -1;
  484. }
  485. stream->setbuf(reinterpret_cast<u8*>(buf), mode, size);
  486. return 0;
  487. }
  488. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/setbuf.html
  489. void setbuf(FILE* stream, char* buf)
  490. {
  491. setvbuf(stream, buf, buf ? _IOFBF : _IONBF, BUFSIZ);
  492. }
  493. void setlinebuf(FILE* stream)
  494. {
  495. setvbuf(stream, nullptr, _IOLBF, 0);
  496. }
  497. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/fileno.html
  498. int fileno(FILE* stream)
  499. {
  500. VERIFY(stream);
  501. ScopedFileLock lock(stream);
  502. return stream->fileno();
  503. }
  504. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/feof.html
  505. int feof(FILE* stream)
  506. {
  507. VERIFY(stream);
  508. ScopedFileLock lock(stream);
  509. return stream->eof();
  510. }
  511. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/fflush.html
  512. int fflush(FILE* stream)
  513. {
  514. if (!stream) {
  515. int rc = 0;
  516. LibC::MutexLocker locker(s_open_streams_lock);
  517. for (auto& file : *s_open_streams) {
  518. ScopedFileLock lock(&file);
  519. rc = file.flush() ? rc : EOF;
  520. }
  521. return rc;
  522. }
  523. ScopedFileLock lock(stream);
  524. return stream->flush() ? 0 : EOF;
  525. }
  526. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/fgets.html
  527. char* fgets(char* buffer, int size, FILE* stream)
  528. {
  529. VERIFY(stream);
  530. ScopedFileLock lock(stream);
  531. bool ok = stream->gets(reinterpret_cast<u8*>(buffer), size);
  532. return ok ? buffer : nullptr;
  533. }
  534. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/fgetc.html
  535. int fgetc(FILE* stream)
  536. {
  537. VERIFY(stream);
  538. char ch;
  539. size_t nread = fread(&ch, sizeof(char), 1, stream);
  540. if (nread == 1)
  541. return ch;
  542. return EOF;
  543. }
  544. int fgetc_unlocked(FILE* stream)
  545. {
  546. VERIFY(stream);
  547. char ch;
  548. size_t nread = fread_unlocked(&ch, sizeof(char), 1, stream);
  549. if (nread == 1)
  550. return ch;
  551. return EOF;
  552. }
  553. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/getc.html
  554. int getc(FILE* stream)
  555. {
  556. return fgetc(stream);
  557. }
  558. int getc_unlocked(FILE* stream)
  559. {
  560. return fgetc_unlocked(stream);
  561. }
  562. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/getchar.html
  563. int getchar()
  564. {
  565. return getc(stdin);
  566. }
  567. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/getdelim.html
  568. ssize_t getdelim(char** lineptr, size_t* n, int delim, FILE* stream)
  569. {
  570. if (!lineptr || !n) {
  571. errno = EINVAL;
  572. return -1;
  573. }
  574. if (*lineptr == nullptr || *n == 0) {
  575. *n = BUFSIZ;
  576. if ((*lineptr = static_cast<char*>(malloc(*n))) == nullptr) {
  577. return -1;
  578. }
  579. }
  580. char* ptr;
  581. char* eptr;
  582. for (ptr = *lineptr, eptr = *lineptr + *n;;) {
  583. int c = fgetc(stream);
  584. if (c == -1) {
  585. if (feof(stream)) {
  586. *ptr = '\0';
  587. return ptr == *lineptr ? -1 : ptr - *lineptr;
  588. } else {
  589. return -1;
  590. }
  591. }
  592. *ptr++ = c;
  593. if (c == delim) {
  594. *ptr = '\0';
  595. return ptr - *lineptr;
  596. }
  597. if (ptr + 2 >= eptr) {
  598. char* nbuf;
  599. size_t nbuf_sz = *n * 2;
  600. ssize_t d = ptr - *lineptr;
  601. if ((nbuf = static_cast<char*>(realloc(*lineptr, nbuf_sz))) == nullptr) {
  602. return -1;
  603. }
  604. *lineptr = nbuf;
  605. *n = nbuf_sz;
  606. eptr = nbuf + nbuf_sz;
  607. ptr = nbuf + d;
  608. }
  609. }
  610. }
  611. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/getline.html
  612. ssize_t getline(char** lineptr, size_t* n, FILE* stream)
  613. {
  614. return getdelim(lineptr, n, '\n', stream);
  615. }
  616. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/ungetc.html
  617. int ungetc(int c, FILE* stream)
  618. {
  619. VERIFY(stream);
  620. ScopedFileLock lock(stream);
  621. bool ok = stream->ungetc(c);
  622. return ok ? c : EOF;
  623. }
  624. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/fputc.html
  625. int fputc(int ch, FILE* stream)
  626. {
  627. VERIFY(stream);
  628. u8 byte = ch;
  629. ScopedFileLock lock(stream);
  630. size_t nwritten = stream->write(&byte, 1);
  631. if (nwritten == 0)
  632. return EOF;
  633. VERIFY(nwritten == 1);
  634. return byte;
  635. }
  636. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/putc.html
  637. int putc(int ch, FILE* stream)
  638. {
  639. return fputc(ch, stream);
  640. }
  641. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/putchar.html
  642. int putchar(int ch)
  643. {
  644. return putc(ch, stdout);
  645. }
  646. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/fputs.html
  647. int fputs(char const* s, FILE* stream)
  648. {
  649. VERIFY(stream);
  650. size_t len = strlen(s);
  651. ScopedFileLock lock(stream);
  652. size_t nwritten = stream->write(reinterpret_cast<u8 const*>(s), len);
  653. if (nwritten < len)
  654. return EOF;
  655. return 1;
  656. }
  657. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/puts.html
  658. int puts(char const* s)
  659. {
  660. int rc = fputs(s, stdout);
  661. if (rc == EOF)
  662. return EOF;
  663. return fputc('\n', stdout);
  664. }
  665. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/clearerr.html
  666. void clearerr(FILE* stream)
  667. {
  668. VERIFY(stream);
  669. ScopedFileLock lock(stream);
  670. stream->clear_err();
  671. }
  672. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/ferror.html
  673. int ferror(FILE* stream)
  674. {
  675. VERIFY(stream);
  676. ScopedFileLock lock(stream);
  677. return stream->error();
  678. }
  679. size_t fread_unlocked(void* ptr, size_t size, size_t nmemb, FILE* stream)
  680. {
  681. VERIFY(stream);
  682. VERIFY(!Checked<size_t>::multiplication_would_overflow(size, nmemb));
  683. size_t nread = stream->read(reinterpret_cast<u8*>(ptr), size * nmemb);
  684. if (!nread)
  685. return 0;
  686. return nread / size;
  687. }
  688. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/fread.html
  689. size_t fread(void* ptr, size_t size, size_t nmemb, FILE* stream)
  690. {
  691. VERIFY(stream);
  692. ScopedFileLock lock(stream);
  693. return fread_unlocked(ptr, size, nmemb, stream);
  694. }
  695. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/fwrite.html
  696. size_t fwrite(void const* ptr, size_t size, size_t nmemb, FILE* stream)
  697. {
  698. VERIFY(stream);
  699. VERIFY(!Checked<size_t>::multiplication_would_overflow(size, nmemb));
  700. ScopedFileLock lock(stream);
  701. size_t nwritten = stream->write(reinterpret_cast<u8 const*>(ptr), size * nmemb);
  702. if (!nwritten)
  703. return 0;
  704. return nwritten / size;
  705. }
  706. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/fseek.html
  707. int fseek(FILE* stream, long offset, int whence)
  708. {
  709. VERIFY(stream);
  710. ScopedFileLock lock(stream);
  711. return stream->seek(offset, whence);
  712. }
  713. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/fseeko.html
  714. int fseeko(FILE* stream, off_t offset, int whence)
  715. {
  716. VERIFY(stream);
  717. ScopedFileLock lock(stream);
  718. return stream->seek(offset, whence);
  719. }
  720. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/ftell.html
  721. long ftell(FILE* stream)
  722. {
  723. VERIFY(stream);
  724. ScopedFileLock lock(stream);
  725. return stream->tell();
  726. }
  727. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/ftello.html
  728. off_t ftello(FILE* stream)
  729. {
  730. VERIFY(stream);
  731. ScopedFileLock lock(stream);
  732. return stream->tell();
  733. }
  734. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/fgetpos.html
  735. int fgetpos(FILE* stream, fpos_t* pos)
  736. {
  737. VERIFY(stream);
  738. VERIFY(pos);
  739. ScopedFileLock lock(stream);
  740. off_t val = stream->tell();
  741. if (val == -1L)
  742. return 1;
  743. *pos = val;
  744. return 0;
  745. }
  746. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/fsetpos.html
  747. int fsetpos(FILE* stream, fpos_t const* pos)
  748. {
  749. VERIFY(stream);
  750. VERIFY(pos);
  751. ScopedFileLock lock(stream);
  752. return stream->seek(*pos, SEEK_SET);
  753. }
  754. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/rewind.html
  755. void rewind(FILE* stream)
  756. {
  757. fseek(stream, 0, SEEK_SET);
  758. clearerr(stream);
  759. }
  760. ALWAYS_INLINE void stdout_putch(char*&, char ch)
  761. {
  762. putchar(ch);
  763. }
  764. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/vfprintf.html
  765. int vfprintf(FILE* stream, char const* fmt, va_list ap)
  766. {
  767. return printf_internal([stream](auto, char ch) { fputc(ch, stream); }, nullptr, fmt, ap);
  768. }
  769. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/fprintf.html
  770. int fprintf(FILE* stream, char const* fmt, ...)
  771. {
  772. va_list ap;
  773. va_start(ap, fmt);
  774. int ret = vfprintf(stream, fmt, ap);
  775. va_end(ap);
  776. return ret;
  777. }
  778. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/vprintf.html
  779. int vprintf(char const* fmt, va_list ap)
  780. {
  781. return printf_internal(stdout_putch, nullptr, fmt, ap);
  782. }
  783. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/printf.html
  784. int printf(char const* fmt, ...)
  785. {
  786. va_list ap;
  787. va_start(ap, fmt);
  788. int ret = vprintf(fmt, ap);
  789. va_end(ap);
  790. return ret;
  791. }
  792. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/vasprintf.html
  793. int vasprintf(char** strp, char const* fmt, va_list ap)
  794. {
  795. StringBuilder builder;
  796. builder.appendvf(fmt, ap);
  797. VERIFY(builder.length() <= NumericLimits<int>::max());
  798. int length = builder.length();
  799. *strp = strdup(builder.to_string().characters());
  800. return length;
  801. }
  802. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/asprintf.html
  803. int asprintf(char** strp, char const* fmt, ...)
  804. {
  805. StringBuilder builder;
  806. va_list ap;
  807. va_start(ap, fmt);
  808. builder.appendvf(fmt, ap);
  809. va_end(ap);
  810. VERIFY(builder.length() <= NumericLimits<int>::max());
  811. int length = builder.length();
  812. *strp = strdup(builder.to_string().characters());
  813. return length;
  814. }
  815. static void buffer_putch(char*& bufptr, char ch)
  816. {
  817. *bufptr++ = ch;
  818. }
  819. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/vsprintf.html
  820. int vsprintf(char* buffer, char const* fmt, va_list ap)
  821. {
  822. int ret = printf_internal(buffer_putch, buffer, fmt, ap);
  823. buffer[ret] = '\0';
  824. return ret;
  825. }
  826. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/sprintf.html
  827. int sprintf(char* buffer, char const* fmt, ...)
  828. {
  829. va_list ap;
  830. va_start(ap, fmt);
  831. int ret = vsprintf(buffer, fmt, ap);
  832. va_end(ap);
  833. return ret;
  834. }
  835. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/vsnprintf.html
  836. int vsnprintf(char* buffer, size_t size, char const* fmt, va_list ap)
  837. {
  838. size_t space_remaining = 0;
  839. if (size) {
  840. space_remaining = size - 1;
  841. } else {
  842. space_remaining = 0;
  843. }
  844. auto sized_buffer_putch = [&](char*& bufptr, char ch) {
  845. if (space_remaining) {
  846. *bufptr++ = ch;
  847. --space_remaining;
  848. }
  849. };
  850. int ret = printf_internal(sized_buffer_putch, buffer, fmt, ap);
  851. if (space_remaining) {
  852. buffer[ret] = '\0';
  853. } else if (size > 0) {
  854. buffer[size - 1] = '\0';
  855. }
  856. return ret;
  857. }
  858. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/snprintf.html
  859. int snprintf(char* buffer, size_t size, char const* fmt, ...)
  860. {
  861. va_list ap;
  862. va_start(ap, fmt);
  863. int ret = vsnprintf(buffer, size, fmt, ap);
  864. va_end(ap);
  865. return ret;
  866. }
  867. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/perror.html
  868. void perror(char const* s)
  869. {
  870. int saved_errno = errno;
  871. dbgln("perror(): {}: {}", s, strerror(saved_errno));
  872. warnln("{}: {}", s, strerror(saved_errno));
  873. }
  874. static int parse_mode(char const* mode)
  875. {
  876. int flags = 0;
  877. // NOTE: rt is a non-standard mode which opens a file for read, explicitly
  878. // specifying that it's a text file
  879. for (auto* ptr = mode; *ptr; ++ptr) {
  880. switch (*ptr) {
  881. case 'r':
  882. flags |= O_RDONLY;
  883. break;
  884. case 'w':
  885. flags |= O_WRONLY | O_CREAT | O_TRUNC;
  886. break;
  887. case 'a':
  888. flags |= O_WRONLY | O_APPEND | O_CREAT;
  889. break;
  890. case '+':
  891. flags |= O_RDWR;
  892. break;
  893. case 'e':
  894. flags |= O_CLOEXEC;
  895. break;
  896. case 'b':
  897. // Ok...
  898. break;
  899. case 't':
  900. // Ok...
  901. break;
  902. default:
  903. dbgln("Potentially unsupported fopen mode _{}_ (because of '{}')", mode, *ptr);
  904. }
  905. }
  906. return flags;
  907. }
  908. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/fopen.html
  909. FILE* fopen(char const* pathname, char const* mode)
  910. {
  911. int flags = parse_mode(mode);
  912. int fd = open(pathname, flags, 0666);
  913. if (fd < 0)
  914. return nullptr;
  915. return FILE::create(fd, flags);
  916. }
  917. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/freopen.html
  918. FILE* freopen(char const* pathname, char const* mode, FILE* stream)
  919. {
  920. VERIFY(stream);
  921. if (!pathname) {
  922. // FIXME: Someone should probably implement this path.
  923. TODO();
  924. }
  925. int flags = parse_mode(mode);
  926. int fd = open(pathname, flags, 0666);
  927. if (fd < 0)
  928. return nullptr;
  929. stream->reopen(fd, flags);
  930. return stream;
  931. }
  932. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/fdopen.html
  933. FILE* fdopen(int fd, char const* mode)
  934. {
  935. int flags = parse_mode(mode);
  936. // FIXME: Verify that the mode matches how fd is already open.
  937. if (fd < 0)
  938. return nullptr;
  939. return FILE::create(fd, flags);
  940. }
  941. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/fmemopen.html
  942. FILE* fmemopen(void*, size_t, char const*)
  943. {
  944. // FIXME: Implement me :^)
  945. TODO();
  946. }
  947. static inline bool is_default_stream(FILE* stream)
  948. {
  949. return stream == stdin || stream == stdout || stream == stderr;
  950. }
  951. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/fclose.html
  952. int fclose(FILE* stream)
  953. {
  954. VERIFY(stream);
  955. bool ok;
  956. {
  957. ScopedFileLock lock(stream);
  958. ok = stream->close();
  959. }
  960. ScopedValueRollback errno_restorer(errno);
  961. {
  962. LibC::MutexLocker locker(s_open_streams_lock);
  963. s_open_streams->remove(*stream);
  964. }
  965. stream->~FILE();
  966. if (!is_default_stream(stream))
  967. free(stream);
  968. return ok ? 0 : EOF;
  969. }
  970. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/rename.html
  971. int rename(char const* oldpath, char const* newpath)
  972. {
  973. if (!oldpath || !newpath) {
  974. errno = EFAULT;
  975. return -1;
  976. }
  977. Syscall::SC_rename_params params { { oldpath, strlen(oldpath) }, { newpath, strlen(newpath) } };
  978. int rc = syscall(SC_rename, &params);
  979. __RETURN_WITH_ERRNO(rc, rc, -1);
  980. }
  981. void dbgputstr(char const* characters, size_t length)
  982. {
  983. syscall(SC_dbgputstr, characters, length);
  984. }
  985. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/tmpnam.html
  986. char* tmpnam(char*)
  987. {
  988. dbgln("FIXME: Implement tmpnam()");
  989. TODO();
  990. }
  991. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/popen.html
  992. FILE* popen(char const* command, char const* type)
  993. {
  994. if (!type || (*type != 'r' && *type != 'w')) {
  995. errno = EINVAL;
  996. return nullptr;
  997. }
  998. int pipe_fds[2];
  999. if (pipe(pipe_fds) < 0) {
  1000. ScopedValueRollback rollback(errno);
  1001. perror("pipe");
  1002. return nullptr;
  1003. }
  1004. pid_t child_pid = fork();
  1005. if (child_pid < 0) {
  1006. ScopedValueRollback rollback(errno);
  1007. perror("fork");
  1008. close(pipe_fds[0]);
  1009. close(pipe_fds[1]);
  1010. return nullptr;
  1011. } else if (child_pid == 0) {
  1012. if (*type == 'r') {
  1013. if (dup2(pipe_fds[1], STDOUT_FILENO) < 0) {
  1014. perror("dup2");
  1015. exit(1);
  1016. }
  1017. close(pipe_fds[0]);
  1018. close(pipe_fds[1]);
  1019. } else if (*type == 'w') {
  1020. if (dup2(pipe_fds[0], STDIN_FILENO) < 0) {
  1021. perror("dup2");
  1022. exit(1);
  1023. }
  1024. close(pipe_fds[0]);
  1025. close(pipe_fds[1]);
  1026. }
  1027. if (execl("/bin/sh", "sh", "-c", command, nullptr) < 0)
  1028. perror("execl");
  1029. exit(1);
  1030. }
  1031. FILE* file = nullptr;
  1032. if (*type == 'r') {
  1033. file = FILE::create(pipe_fds[0], O_RDONLY);
  1034. close(pipe_fds[1]);
  1035. } else if (*type == 'w') {
  1036. file = FILE::create(pipe_fds[1], O_WRONLY);
  1037. close(pipe_fds[0]);
  1038. }
  1039. file->set_popen_child(child_pid);
  1040. return file;
  1041. }
  1042. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/pclose.html
  1043. int pclose(FILE* stream)
  1044. {
  1045. VERIFY(stream);
  1046. VERIFY(stream->popen_child() != 0);
  1047. int wstatus = 0;
  1048. if (waitpid(stream->popen_child(), &wstatus, 0) < 0)
  1049. return -1;
  1050. return wstatus;
  1051. }
  1052. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/remove.html
  1053. int remove(char const* pathname)
  1054. {
  1055. if (unlink(pathname) < 0) {
  1056. if (errno == EISDIR)
  1057. return rmdir(pathname);
  1058. return -1;
  1059. }
  1060. return 0;
  1061. }
  1062. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/scanf.html
  1063. int scanf(char const* fmt, ...)
  1064. {
  1065. va_list ap;
  1066. va_start(ap, fmt);
  1067. int count = vfscanf(stdin, fmt, ap);
  1068. va_end(ap);
  1069. return count;
  1070. }
  1071. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/fscanf.html
  1072. int fscanf(FILE* stream, char const* fmt, ...)
  1073. {
  1074. va_list ap;
  1075. va_start(ap, fmt);
  1076. int count = vfscanf(stream, fmt, ap);
  1077. va_end(ap);
  1078. return count;
  1079. }
  1080. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/sscanf.html
  1081. int sscanf(char const* buffer, char const* fmt, ...)
  1082. {
  1083. va_list ap;
  1084. va_start(ap, fmt);
  1085. int count = vsscanf(buffer, fmt, ap);
  1086. va_end(ap);
  1087. return count;
  1088. }
  1089. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/vfscanf.html
  1090. int vfscanf(FILE* stream, char const* fmt, va_list ap)
  1091. {
  1092. char buffer[BUFSIZ];
  1093. if (!fgets(buffer, sizeof(buffer) - 1, stream))
  1094. return -1;
  1095. return vsscanf(buffer, fmt, ap);
  1096. }
  1097. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/vscanf.html
  1098. int vscanf(char const* fmt, va_list ap)
  1099. {
  1100. return vfscanf(stdin, fmt, ap);
  1101. }
  1102. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/flockfile.html
  1103. void flockfile(FILE* filehandle)
  1104. {
  1105. VERIFY(filehandle);
  1106. filehandle->lock();
  1107. }
  1108. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/funlockfile.html
  1109. void funlockfile(FILE* filehandle)
  1110. {
  1111. VERIFY(filehandle);
  1112. filehandle->unlock();
  1113. }
  1114. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/tmpfile.html
  1115. FILE* tmpfile()
  1116. {
  1117. char tmp_path[] = "/tmp/XXXXXX";
  1118. int fd = mkstemp(tmp_path);
  1119. if (fd < 0)
  1120. return nullptr;
  1121. // FIXME: instead of using this hack, implement with O_TMPFILE or similar
  1122. unlink(tmp_path);
  1123. return fdopen(fd, "rw");
  1124. }
  1125. size_t __fpending(FILE* stream)
  1126. {
  1127. ScopedFileLock lock(stream);
  1128. return stream->pending();
  1129. }
  1130. int __freading(FILE* stream)
  1131. {
  1132. ScopedFileLock lock(stream);
  1133. if ((stream->mode() & O_RDWR) == O_RDONLY) {
  1134. return 1;
  1135. }
  1136. return (stream->flags() & FILE::Flags::LastRead);
  1137. }
  1138. int __fwriting(FILE* stream)
  1139. {
  1140. ScopedFileLock lock(stream);
  1141. if ((stream->mode() & O_RDWR) == O_WRONLY) {
  1142. return 1;
  1143. }
  1144. return (stream->flags() & FILE::Flags::LastWrite);
  1145. }
  1146. void __fpurge(FILE* stream)
  1147. {
  1148. ScopedFileLock lock(stream);
  1149. stream->purge();
  1150. }
  1151. char const* __freadptr(FILE* stream, size_t* sizep)
  1152. {
  1153. VERIFY(stream);
  1154. VERIFY(sizep);
  1155. ScopedFileLock lock(stream);
  1156. size_t available_size;
  1157. u8 const* ptr = stream->readptr(available_size);
  1158. if (available_size == 0)
  1159. return nullptr;
  1160. *sizep = available_size;
  1161. return reinterpret_cast<char const*>(ptr);
  1162. }
  1163. }
  1164. template bool FILE::gets<u8>(u8*, size_t);
  1165. template bool FILE::gets<u32>(u32*, size_t);