stdio.cpp 26 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/LogStream.h>
  27. #include <AK/PrintfImplementation.h>
  28. #include <AK/ScopedValueRollback.h>
  29. #include <AK/StdLibExtras.h>
  30. #include <AK/kmalloc.h>
  31. #include <Kernel/Syscall.h>
  32. #include <assert.h>
  33. #include <errno.h>
  34. #include <fcntl.h>
  35. #include <stdarg.h>
  36. #include <stdio.h>
  37. #include <stdlib.h>
  38. #include <string.h>
  39. #include <sys/types.h>
  40. #include <sys/wait.h>
  41. #include <unistd.h>
  42. struct FILE {
  43. public:
  44. FILE(int fd, int mode)
  45. : m_fd(fd)
  46. , m_mode(mode)
  47. {
  48. }
  49. ~FILE();
  50. static FILE* create(int fd, int mode);
  51. void setbuf(u8* data, int mode, size_t size) { m_buffer.setbuf(data, mode, size); }
  52. bool flush();
  53. bool close();
  54. int fileno() const { return m_fd; }
  55. bool eof() const { return m_eof; }
  56. int error() const { return m_error; }
  57. void clear_err() { m_error = 0; }
  58. size_t read(u8*, size_t);
  59. size_t write(const u8*, size_t);
  60. bool gets(u8*, size_t);
  61. bool ungetc(u8 byte) { return m_buffer.enqueue_front(byte); }
  62. int seek(long offset, int whence);
  63. long tell();
  64. pid_t popen_child() { return m_popen_child; }
  65. void set_popen_child(pid_t child_pid) { m_popen_child = child_pid; }
  66. private:
  67. struct Buffer {
  68. // A ringbuffer that also transparently implements ungetc().
  69. public:
  70. ~Buffer();
  71. int mode() const { return m_mode; }
  72. void setbuf(u8* data, int mode, size_t size);
  73. // Make sure to call realize() before enqueuing any data.
  74. // Dequeuing can be attempted without it.
  75. void realize(int fd);
  76. void drop();
  77. bool may_use() const { return m_ungotten || m_mode != _IONBF; }
  78. bool is_not_empty() const { return m_ungotten || !m_empty; }
  79. const u8* begin_dequeue(size_t& available_size) const;
  80. void did_dequeue(size_t actual_size);
  81. u8* begin_enqueue(size_t& available_size) const;
  82. void did_enqueue(size_t actual_size);
  83. bool enqueue_front(u8 byte);
  84. private:
  85. // Note: the fields here are arranged this way
  86. // to make sizeof(Buffer) smaller.
  87. u8* m_data { nullptr };
  88. size_t m_capacity { BUFSIZ };
  89. size_t m_begin { 0 };
  90. size_t m_end { 0 };
  91. int m_mode { -1 };
  92. u8 m_unget_buffer { 0 };
  93. bool m_ungotten : 1 { false };
  94. bool m_data_is_malloced : 1 { false };
  95. // When m_begin == m_end, we want to distinguish whether
  96. // the buffer is full or empty.
  97. bool m_empty : 1 { true };
  98. };
  99. // Read or write using the underlying fd, bypassing the buffer.
  100. ssize_t do_read(u8*, size_t);
  101. ssize_t do_write(const u8*, size_t);
  102. // Read some data into the buffer.
  103. bool read_into_buffer();
  104. // Flush *some* data from the buffer.
  105. bool write_from_buffer();
  106. int m_fd { -1 };
  107. int m_mode { 0 };
  108. int m_error { 0 };
  109. bool m_eof { false };
  110. pid_t m_popen_child { -1 };
  111. Buffer m_buffer;
  112. };
  113. FILE::~FILE()
  114. {
  115. bool already_closed = m_fd == -1;
  116. ASSERT(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. m_buffer.drop();
  148. }
  149. return true;
  150. }
  151. ssize_t FILE::do_read(u8* data, size_t size)
  152. {
  153. int nread = ::read(m_fd, data, size);
  154. if (nread < 0) {
  155. m_error = errno;
  156. } else if (nread == 0) {
  157. m_eof = true;
  158. }
  159. return nread;
  160. }
  161. ssize_t FILE::do_write(const u8* data, size_t size)
  162. {
  163. int nwritten = ::write(m_fd, data, size);
  164. if (nwritten < 0)
  165. m_error = errno;
  166. return nwritten;
  167. }
  168. bool FILE::read_into_buffer()
  169. {
  170. m_buffer.realize(m_fd);
  171. size_t available_size;
  172. u8* data = m_buffer.begin_enqueue(available_size);
  173. // If we want to read, the buffer must have some space!
  174. ASSERT(available_size);
  175. ssize_t nread = do_read(data, available_size);
  176. if (nread <= 0)
  177. return false;
  178. m_buffer.did_enqueue(nread);
  179. return true;
  180. }
  181. bool FILE::write_from_buffer()
  182. {
  183. size_t size;
  184. const u8* data = m_buffer.begin_dequeue(size);
  185. // If we want to write, the buffer must have something in it!
  186. ASSERT(size);
  187. ssize_t nwritten = do_write(data, size);
  188. if (nwritten < 0)
  189. return false;
  190. m_buffer.did_dequeue(nwritten);
  191. return true;
  192. }
  193. size_t FILE::read(u8* data, size_t size)
  194. {
  195. size_t total_read = 0;
  196. while (size > 0) {
  197. size_t actual_size;
  198. if (m_buffer.may_use()) {
  199. // Let's see if the buffer has something queued for us.
  200. size_t queued_size;
  201. const u8* queued_data = m_buffer.begin_dequeue(queued_size);
  202. if (queued_size == 0) {
  203. // Nothing buffered; we're going to have to read some.
  204. bool read_some_more = read_into_buffer();
  205. if (read_some_more) {
  206. // Great, now try this again.
  207. continue;
  208. }
  209. return total_read;
  210. }
  211. actual_size = min(size, queued_size);
  212. memcpy(data, queued_data, actual_size);
  213. m_buffer.did_dequeue(actual_size);
  214. } else {
  215. // Read directly into the user buffer.
  216. ssize_t nread = do_read(data, size);
  217. if (nread <= 0)
  218. return total_read;
  219. actual_size = nread;
  220. }
  221. total_read += actual_size;
  222. data += actual_size;
  223. size -= actual_size;
  224. }
  225. return total_read;
  226. }
  227. size_t FILE::write(const u8* data, size_t size)
  228. {
  229. size_t total_written = 0;
  230. while (size > 0) {
  231. size_t actual_size;
  232. if (m_buffer.may_use()) {
  233. m_buffer.realize(m_fd);
  234. // Try writing into the buffer.
  235. size_t available_size;
  236. u8* buffer_data = m_buffer.begin_enqueue(available_size);
  237. if (available_size == 0) {
  238. // There's no space in the buffer; we're going to free some.
  239. bool freed_some_space = write_from_buffer();
  240. if (freed_some_space) {
  241. // Great, now try this again.
  242. continue;
  243. }
  244. return total_written;
  245. }
  246. actual_size = min(size, available_size);
  247. memcpy(buffer_data, data, actual_size);
  248. m_buffer.did_enqueue(actual_size);
  249. // See if we have to flush it.
  250. if (m_buffer.mode() == _IOLBF) {
  251. bool includes_newline = memchr(data, '\n', actual_size);
  252. if (includes_newline)
  253. flush();
  254. }
  255. } else {
  256. // Write directly from the user buffer.
  257. ssize_t nwritten = do_write(data, size);
  258. if (nwritten < 0)
  259. return total_written;
  260. actual_size = nwritten;
  261. }
  262. total_written += actual_size;
  263. data += actual_size;
  264. size -= actual_size;
  265. }
  266. return total_written;
  267. }
  268. bool FILE::gets(u8* data, size_t size)
  269. {
  270. // gets() is a lot like read(), but it is different enough in how it
  271. // processes newlines and null-terminates the buffer that it deserves a
  272. // separate implementation.
  273. size_t total_read = 0;
  274. while (size > 1) {
  275. if (m_buffer.may_use()) {
  276. // Let's see if the buffer has something queued for us.
  277. size_t queued_size;
  278. const u8* queued_data = m_buffer.begin_dequeue(queued_size);
  279. if (queued_size == 0) {
  280. // Nothing buffered; we're going to have to read some.
  281. bool read_some_more = read_into_buffer();
  282. if (read_some_more) {
  283. // Great, now try this again.
  284. continue;
  285. }
  286. *data = 0;
  287. return total_read > 0;
  288. }
  289. size_t actual_size = min(size - 1, queued_size);
  290. u8* newline = reinterpret_cast<u8*>(memchr(queued_data, '\n', actual_size));
  291. if (newline)
  292. actual_size = newline - queued_data + 1;
  293. memcpy(data, queued_data, actual_size);
  294. m_buffer.did_dequeue(actual_size);
  295. total_read += actual_size;
  296. data += actual_size;
  297. size -= actual_size;
  298. if (newline)
  299. break;
  300. } else {
  301. // Sadly, we have to actually read these characters one by one.
  302. u8 byte;
  303. ssize_t nread = do_read(&byte, 1);
  304. if (nread <= 0) {
  305. *data = 0;
  306. return total_read > 0;
  307. }
  308. ASSERT(nread == 1);
  309. *data = byte;
  310. total_read++;
  311. data++;
  312. size--;
  313. if (byte == '\n')
  314. break;
  315. }
  316. }
  317. *data = 0;
  318. return total_read > 0;
  319. }
  320. int FILE::seek(long offset, int whence)
  321. {
  322. bool ok = flush();
  323. if (!ok)
  324. return -1;
  325. off_t off = lseek(m_fd, offset, whence);
  326. if (off < 0) {
  327. // Note: do not set m_error.
  328. return off;
  329. }
  330. m_eof = false;
  331. return 0;
  332. }
  333. long FILE::tell()
  334. {
  335. bool ok = flush();
  336. if (!ok)
  337. return -1;
  338. return lseek(m_fd, 0, SEEK_CUR);
  339. }
  340. FILE::Buffer::~Buffer()
  341. {
  342. if (m_data_is_malloced)
  343. free(m_data);
  344. }
  345. void FILE::Buffer::realize(int fd)
  346. {
  347. if (m_mode == -1)
  348. m_mode = isatty(fd) ? _IOLBF : _IOFBF;
  349. if (m_mode != _IONBF && m_data == nullptr) {
  350. m_data = reinterpret_cast<u8*>(malloc(m_capacity));
  351. m_data_is_malloced = true;
  352. }
  353. }
  354. void FILE::Buffer::setbuf(u8* data, int mode, size_t size)
  355. {
  356. drop();
  357. m_mode = mode;
  358. if (data != nullptr) {
  359. m_data = data;
  360. m_capacity = size;
  361. }
  362. }
  363. void FILE::Buffer::drop()
  364. {
  365. if (m_data_is_malloced) {
  366. free(m_data);
  367. m_data = nullptr;
  368. m_data_is_malloced = false;
  369. }
  370. m_begin = m_end = 0;
  371. m_empty = true;
  372. m_ungotten = false;
  373. }
  374. const u8* FILE::Buffer::begin_dequeue(size_t& available_size) const
  375. {
  376. if (m_ungotten) {
  377. available_size = 1;
  378. return &m_unget_buffer;
  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. ASSERT(actual_size > 0);
  393. if (m_ungotten) {
  394. ASSERT(actual_size == 1);
  395. m_ungotten = false;
  396. return;
  397. }
  398. m_begin += actual_size;
  399. ASSERT(m_begin <= m_capacity);
  400. if (m_begin == m_capacity) {
  401. // Wrap around.
  402. m_begin = 0;
  403. }
  404. if (m_begin == m_end) {
  405. m_empty = true;
  406. // As an optimization, move both pointers to the beginning of the
  407. // buffer, so that more consecutive space is available next time.
  408. m_begin = m_end = 0;
  409. }
  410. }
  411. u8* FILE::Buffer::begin_enqueue(size_t& available_size) const
  412. {
  413. ASSERT(m_data != nullptr);
  414. if (m_begin < m_end || m_empty)
  415. available_size = m_capacity - m_end;
  416. else
  417. available_size = m_begin - m_end;
  418. return const_cast<u8*>(&m_data[m_end]);
  419. }
  420. void FILE::Buffer::did_enqueue(size_t actual_size)
  421. {
  422. ASSERT(m_data != nullptr);
  423. ASSERT(actual_size > 0);
  424. m_end += actual_size;
  425. ASSERT(m_end <= m_capacity);
  426. if (m_end == m_capacity) {
  427. // Wrap around.
  428. m_end = 0;
  429. }
  430. m_empty = false;
  431. }
  432. bool FILE::Buffer::enqueue_front(u8 byte)
  433. {
  434. if (m_ungotten) {
  435. // Sorry, the place is already taken!
  436. return false;
  437. }
  438. m_ungotten = true;
  439. m_unget_buffer = byte;
  440. return true;
  441. }
  442. extern "C" {
  443. static u8 default_streams[3][sizeof(FILE)];
  444. FILE* stdin = reinterpret_cast<FILE*>(&default_streams[0]);
  445. FILE* stdout = reinterpret_cast<FILE*>(&default_streams[1]);
  446. FILE* stderr = reinterpret_cast<FILE*>(&default_streams[2]);
  447. void __stdio_init()
  448. {
  449. new (stdin) FILE(0, O_RDONLY);
  450. new (stdout) FILE(1, O_WRONLY);
  451. new (stderr) FILE(2, O_WRONLY);
  452. stderr->setbuf(nullptr, _IONBF, 0);
  453. }
  454. int setvbuf(FILE* stream, char* buf, int mode, size_t size)
  455. {
  456. ASSERT(stream);
  457. if (mode != _IONBF && mode != _IOLBF && mode != _IOFBF) {
  458. errno = EINVAL;
  459. return -1;
  460. }
  461. stream->setbuf(reinterpret_cast<u8*>(buf), mode, size);
  462. return 0;
  463. }
  464. void setbuf(FILE* stream, char* buf)
  465. {
  466. setvbuf(stream, buf, buf ? _IOFBF : _IONBF, BUFSIZ);
  467. }
  468. void setlinebuf(FILE* stream)
  469. {
  470. setvbuf(stream, nullptr, _IOLBF, 0);
  471. }
  472. int fileno(FILE* stream)
  473. {
  474. ASSERT(stream);
  475. return stream->fileno();
  476. }
  477. int feof(FILE* stream)
  478. {
  479. ASSERT(stream);
  480. return stream->eof();
  481. }
  482. int fflush(FILE* stream)
  483. {
  484. if (!stream) {
  485. dbg() << "FIXME: fflush(nullptr) should flush all open streams";
  486. return 0;
  487. }
  488. return stream->flush() ? 0 : EOF;
  489. }
  490. char* fgets(char* buffer, int size, FILE* stream)
  491. {
  492. ASSERT(stream);
  493. bool ok = stream->gets(reinterpret_cast<u8*>(buffer), size);
  494. return ok ? buffer : nullptr;
  495. }
  496. int fgetc(FILE* stream)
  497. {
  498. ASSERT(stream);
  499. char ch;
  500. size_t nread = fread(&ch, sizeof(char), 1, stream);
  501. if (nread == 1)
  502. return ch;
  503. return EOF;
  504. }
  505. int getc(FILE* stream)
  506. {
  507. return fgetc(stream);
  508. }
  509. int getc_unlocked(FILE* stream)
  510. {
  511. return fgetc(stream);
  512. }
  513. int getchar()
  514. {
  515. return getc(stdin);
  516. }
  517. ssize_t getdelim(char** lineptr, size_t* n, int delim, FILE* stream)
  518. {
  519. char *ptr, *eptr;
  520. if (*lineptr == nullptr || *n == 0) {
  521. *n = BUFSIZ;
  522. if ((*lineptr = static_cast<char*>(malloc(*n))) == nullptr) {
  523. return -1;
  524. }
  525. }
  526. for (ptr = *lineptr, eptr = *lineptr + *n;;) {
  527. int c = fgetc(stream);
  528. if (c == -1) {
  529. if (feof(stream)) {
  530. *ptr = '\0';
  531. return ptr == *lineptr ? -1 : ptr - *lineptr;
  532. } else {
  533. return -1;
  534. }
  535. }
  536. *ptr++ = c;
  537. if (c == delim) {
  538. *ptr = '\0';
  539. return ptr - *lineptr;
  540. }
  541. if (ptr + 2 >= eptr) {
  542. char* nbuf;
  543. size_t nbuf_sz = *n * 2;
  544. ssize_t d = ptr - *lineptr;
  545. if ((nbuf = static_cast<char*>(realloc(*lineptr, nbuf_sz))) == nullptr) {
  546. return -1;
  547. }
  548. *lineptr = nbuf;
  549. *n = nbuf_sz;
  550. eptr = nbuf + nbuf_sz;
  551. ptr = nbuf + d;
  552. }
  553. }
  554. }
  555. ssize_t getline(char** lineptr, size_t* n, FILE* stream)
  556. {
  557. return getdelim(lineptr, n, '\n', stream);
  558. }
  559. int ungetc(int c, FILE* stream)
  560. {
  561. ASSERT(stream);
  562. bool ok = stream->ungetc(c);
  563. return ok ? c : EOF;
  564. }
  565. int fputc(int ch, FILE* stream)
  566. {
  567. ASSERT(stream);
  568. u8 byte = ch;
  569. size_t nwritten = stream->write(&byte, 1);
  570. if (nwritten == 0)
  571. return EOF;
  572. ASSERT(nwritten == 1);
  573. return byte;
  574. }
  575. int putc(int ch, FILE* stream)
  576. {
  577. return fputc(ch, stream);
  578. }
  579. int putchar(int ch)
  580. {
  581. return putc(ch, stdout);
  582. }
  583. int fputs(const char* s, FILE* stream)
  584. {
  585. ASSERT(stream);
  586. size_t len = strlen(s);
  587. size_t nwritten = stream->write(reinterpret_cast<const u8*>(s), len);
  588. if (nwritten < len)
  589. return EOF;
  590. return 1;
  591. }
  592. int puts(const char* s)
  593. {
  594. int rc = fputs(s, stdout);
  595. if (rc == EOF)
  596. return EOF;
  597. return fputc('\n', stdout);
  598. }
  599. void clearerr(FILE* stream)
  600. {
  601. ASSERT(stream);
  602. stream->clear_err();
  603. }
  604. int ferror(FILE* stream)
  605. {
  606. ASSERT(stream);
  607. return stream->error();
  608. }
  609. size_t fread(void* ptr, size_t size, size_t nmemb, FILE* stream)
  610. {
  611. ASSERT(stream);
  612. ASSERT(!Checked<size_t>::multiplication_would_overflow(size, nmemb));
  613. size_t nread = stream->read(reinterpret_cast<u8*>(ptr), size * nmemb);
  614. return nread / size;
  615. }
  616. size_t fwrite(const void* ptr, size_t size, size_t nmemb, FILE* stream)
  617. {
  618. ASSERT(stream);
  619. ASSERT(!Checked<size_t>::multiplication_would_overflow(size, nmemb));
  620. size_t nwritten = stream->write(reinterpret_cast<const u8*>(ptr), size * nmemb);
  621. return nwritten / size;
  622. }
  623. int fseek(FILE* stream, long offset, int whence)
  624. {
  625. ASSERT(stream);
  626. return stream->seek(offset, whence);
  627. }
  628. long ftell(FILE* stream)
  629. {
  630. ASSERT(stream);
  631. return stream->tell();
  632. }
  633. int fgetpos(FILE* stream, fpos_t* pos)
  634. {
  635. ASSERT(stream);
  636. ASSERT(pos);
  637. long val = stream->tell();
  638. if (val == -1L)
  639. return 1;
  640. *pos = val;
  641. return 0;
  642. }
  643. int fsetpos(FILE* stream, const fpos_t* pos)
  644. {
  645. ASSERT(stream);
  646. ASSERT(pos);
  647. return stream->seek((long)*pos, SEEK_SET);
  648. }
  649. void rewind(FILE* stream)
  650. {
  651. ASSERT(stream);
  652. int rc = stream->seek(0, SEEK_SET);
  653. ASSERT(rc == 0);
  654. }
  655. int dbgprintf(const char* fmt, ...)
  656. {
  657. va_list ap;
  658. va_start(ap, fmt);
  659. int ret = printf_internal([](char*&, char ch) { dbgputch(ch); }, nullptr, fmt, ap);
  660. va_end(ap);
  661. return ret;
  662. }
  663. ALWAYS_INLINE void stdout_putch(char*&, char ch)
  664. {
  665. putchar(ch);
  666. }
  667. static FILE* __current_stream = nullptr;
  668. ALWAYS_INLINE static void stream_putch(char*&, char ch)
  669. {
  670. fputc(ch, __current_stream);
  671. }
  672. int vfprintf(FILE* stream, const char* fmt, va_list ap)
  673. {
  674. __current_stream = stream;
  675. return printf_internal(stream_putch, nullptr, fmt, ap);
  676. }
  677. int fprintf(FILE* stream, const char* fmt, ...)
  678. {
  679. va_list ap;
  680. va_start(ap, fmt);
  681. int ret = vfprintf(stream, fmt, ap);
  682. va_end(ap);
  683. return ret;
  684. }
  685. int vprintf(const char* fmt, va_list ap)
  686. {
  687. return printf_internal(stdout_putch, nullptr, fmt, ap);
  688. }
  689. int printf(const char* fmt, ...)
  690. {
  691. va_list ap;
  692. va_start(ap, fmt);
  693. int ret = vprintf(fmt, ap);
  694. va_end(ap);
  695. return ret;
  696. }
  697. static void buffer_putch(char*& bufptr, char ch)
  698. {
  699. *bufptr++ = ch;
  700. }
  701. int vsprintf(char* buffer, const char* fmt, va_list ap)
  702. {
  703. int ret = printf_internal(buffer_putch, buffer, fmt, ap);
  704. buffer[ret] = '\0';
  705. return ret;
  706. }
  707. int sprintf(char* buffer, const char* fmt, ...)
  708. {
  709. va_list ap;
  710. va_start(ap, fmt);
  711. int ret = vsprintf(buffer, fmt, ap);
  712. va_end(ap);
  713. return ret;
  714. }
  715. static size_t __vsnprintf_space_remaining;
  716. ALWAYS_INLINE void sized_buffer_putch(char*& bufptr, char ch)
  717. {
  718. if (__vsnprintf_space_remaining) {
  719. *bufptr++ = ch;
  720. --__vsnprintf_space_remaining;
  721. }
  722. }
  723. int vsnprintf(char* buffer, size_t size, const char* fmt, va_list ap)
  724. {
  725. __vsnprintf_space_remaining = size;
  726. int ret = printf_internal(sized_buffer_putch, buffer, fmt, ap);
  727. if (__vsnprintf_space_remaining) {
  728. buffer[ret] = '\0';
  729. }
  730. return ret;
  731. }
  732. int snprintf(char* buffer, size_t size, const char* fmt, ...)
  733. {
  734. va_list ap;
  735. va_start(ap, fmt);
  736. int ret = vsnprintf(buffer, size, fmt, ap);
  737. va_end(ap);
  738. return ret;
  739. }
  740. void perror(const char* s)
  741. {
  742. int saved_errno = errno;
  743. dbg() << "perror(): " << s << ": " << strerror(saved_errno);
  744. fprintf(stderr, "%s: %s\n", s, strerror(saved_errno));
  745. }
  746. static int parse_mode(const char* mode)
  747. {
  748. int flags = 0;
  749. // NOTE: rt is a non-standard mode which opens a file for read, explicitly
  750. // specifying that it's a text file
  751. if (!strcmp(mode, "r") || !strcmp(mode, "rb") || !strcmp(mode, "rt"))
  752. flags = O_RDONLY;
  753. else if (!strcmp(mode, "r+") || !strcmp(mode, "rb+"))
  754. flags = O_RDWR;
  755. else if (!strcmp(mode, "w") || !strcmp(mode, "wb"))
  756. flags = O_WRONLY | O_CREAT | O_TRUNC;
  757. else if (!strcmp(mode, "w+") || !strcmp(mode, "wb+"))
  758. flags = O_RDWR | O_CREAT | O_TRUNC;
  759. else if (!strcmp(mode, "a") || !strcmp(mode, "ab"))
  760. flags = O_WRONLY | O_APPEND | O_CREAT;
  761. else if (!strcmp(mode, "a+") || !strcmp(mode, "ab+"))
  762. flags = O_RDWR | O_APPEND | O_CREAT;
  763. else {
  764. dbg() << "Unexpected mode _" << mode << "_";
  765. ASSERT_NOT_REACHED();
  766. }
  767. return flags;
  768. }
  769. FILE* fopen(const char* pathname, const char* mode)
  770. {
  771. int flags = parse_mode(mode);
  772. int fd = open(pathname, flags, 0666);
  773. if (fd < 0)
  774. return nullptr;
  775. return FILE::create(fd, flags);
  776. }
  777. FILE* freopen(const char* pathname, const char* mode, FILE* stream)
  778. {
  779. (void)pathname;
  780. (void)mode;
  781. (void)stream;
  782. ASSERT_NOT_REACHED();
  783. }
  784. FILE* fdopen(int fd, const char* mode)
  785. {
  786. int flags = parse_mode(mode);
  787. // FIXME: Verify that the mode matches how fd is already open.
  788. if (fd < 0)
  789. return nullptr;
  790. return FILE::create(fd, flags);
  791. }
  792. static inline bool is_default_stream(FILE* stream)
  793. {
  794. return stream == stdin || stream == stdout || stream == stderr;
  795. }
  796. int fclose(FILE* stream)
  797. {
  798. ASSERT(stream);
  799. bool ok = stream->close();
  800. ScopedValueRollback errno_restorer(errno);
  801. stream->~FILE();
  802. if (!is_default_stream(stream))
  803. free(stream);
  804. return ok ? 0 : EOF;
  805. }
  806. int rename(const char* oldpath, const char* newpath)
  807. {
  808. if (!oldpath || !newpath) {
  809. errno = EFAULT;
  810. return -1;
  811. }
  812. Syscall::SC_rename_params params { { oldpath, strlen(oldpath) }, { newpath, strlen(newpath) } };
  813. int rc = syscall(SC_rename, &params);
  814. __RETURN_WITH_ERRNO(rc, rc, -1);
  815. }
  816. void dbgputch(char ch)
  817. {
  818. syscall(SC_dbgputch, ch);
  819. }
  820. int dbgputstr(const char* characters, int length)
  821. {
  822. int rc = syscall(SC_dbgputstr, characters, length);
  823. __RETURN_WITH_ERRNO(rc, rc, -1);
  824. }
  825. char* tmpnam(char*)
  826. {
  827. ASSERT_NOT_REACHED();
  828. }
  829. FILE* popen(const char* command, const char* type)
  830. {
  831. if (!type || (*type != 'r' && *type != 'w')) {
  832. errno = EINVAL;
  833. return nullptr;
  834. }
  835. int pipe_fds[2];
  836. int rc = pipe(pipe_fds);
  837. if (rc < 0) {
  838. ScopedValueRollback rollback(errno);
  839. perror("pipe");
  840. return nullptr;
  841. }
  842. pid_t child_pid = fork();
  843. if (child_pid < 0) {
  844. ScopedValueRollback rollback(errno);
  845. perror("fork");
  846. close(pipe_fds[0]);
  847. close(pipe_fds[1]);
  848. return nullptr;
  849. } else if (child_pid == 0) {
  850. if (*type == 'r') {
  851. int rc = dup2(pipe_fds[1], STDOUT_FILENO);
  852. if (rc < 0) {
  853. perror("dup2");
  854. exit(1);
  855. }
  856. close(pipe_fds[0]);
  857. close(pipe_fds[1]);
  858. } else if (*type == 'w') {
  859. int rc = dup2(pipe_fds[0], STDIN_FILENO);
  860. if (rc < 0) {
  861. perror("dup2");
  862. exit(1);
  863. }
  864. close(pipe_fds[0]);
  865. close(pipe_fds[1]);
  866. }
  867. int rc = execl("/bin/sh", "sh", "-c", command, nullptr);
  868. if (rc < 0)
  869. perror("execl");
  870. exit(1);
  871. }
  872. FILE* file = nullptr;
  873. if (*type == 'r') {
  874. file = FILE::create(pipe_fds[0], O_RDONLY);
  875. close(pipe_fds[1]);
  876. } else if (*type == 'w') {
  877. file = FILE::create(pipe_fds[1], O_WRONLY);
  878. close(pipe_fds[0]);
  879. }
  880. file->set_popen_child(child_pid);
  881. return file;
  882. }
  883. int pclose(FILE* stream)
  884. {
  885. ASSERT(stream);
  886. ASSERT(stream->popen_child() != 0);
  887. int wstatus = 0;
  888. int rc = waitpid(stream->popen_child(), &wstatus, 0);
  889. if (rc < 0)
  890. return rc;
  891. return wstatus;
  892. }
  893. int remove(const char* pathname)
  894. {
  895. int rc = unlink(pathname);
  896. if (rc < 0 && errno != EISDIR)
  897. return -1;
  898. return rmdir(pathname);
  899. }
  900. int scanf(const char* fmt, ...)
  901. {
  902. va_list ap;
  903. va_start(ap, fmt);
  904. int count = vfscanf(stdin, fmt, ap);
  905. va_end(ap);
  906. return count;
  907. }
  908. int fscanf(FILE* stream, const char* fmt, ...)
  909. {
  910. va_list ap;
  911. va_start(ap, fmt);
  912. int count = vfscanf(stream, fmt, ap);
  913. va_end(ap);
  914. return count;
  915. }
  916. int sscanf(const char* buffer, const char* fmt, ...)
  917. {
  918. va_list ap;
  919. va_start(ap, fmt);
  920. int count = vsscanf(buffer, fmt, ap);
  921. va_end(ap);
  922. return count;
  923. }
  924. int vfscanf(FILE* stream, const char* fmt, va_list ap)
  925. {
  926. char buffer[BUFSIZ];
  927. if (!fgets(buffer, sizeof(buffer) - 1, stream))
  928. return -1;
  929. return vsscanf(buffer, fmt, ap);
  930. }
  931. void flockfile(FILE* filehandle)
  932. {
  933. (void)filehandle;
  934. dbgprintf("FIXME: Implement flockfile()\n");
  935. }
  936. void funlockfile(FILE* filehandle)
  937. {
  938. (void)filehandle;
  939. dbgprintf("FIXME: Implement funlockfile()\n");
  940. }
  941. FILE* tmpfile()
  942. {
  943. char tmp_path[] = "/tmp/XXXXXX";
  944. if (__generate_unique_filename(tmp_path) < 0)
  945. return nullptr;
  946. int fd = open(tmp_path, O_CREAT | O_EXCL | O_RDWR, S_IWUSR | S_IRUSR);
  947. if (fd < 0)
  948. return nullptr;
  949. // FIXME: instead of using this hack, implement with O_TMPFILE or similar
  950. unlink(tmp_path);
  951. return fdopen(fd, "rw");
  952. }
  953. }