stdio.cpp 29 KB

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