stdio.cpp 34 KB

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