stdio.cpp 28 KB

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