stdio.cpp 33 KB

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