mod.rs 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208
  1. //! stdio implementation for Redox, following http://pubs.opengroup.org/onlinepubs/7908799/xsh/stdio.h.html
  2. use alloc::{
  3. borrow::{Borrow, BorrowMut},
  4. boxed::Box,
  5. vec::Vec,
  6. };
  7. use core::{
  8. cmp,
  9. ffi::VaList as va_list,
  10. fmt::{self, Write as WriteFmt},
  11. i32, mem,
  12. ops::{Deref, DerefMut},
  13. ptr, slice, str,
  14. };
  15. use crate::{
  16. c_str::CStr,
  17. c_vec::CVec,
  18. fs::File,
  19. header::{
  20. errno::{self, STR_ERROR},
  21. fcntl, stdlib,
  22. string::{self, strlen},
  23. unistd,
  24. },
  25. io::{self, BufRead, BufWriter, LineWriter, Read, Write},
  26. platform::{self, errno, types::*, Pal, Sys, WriteByte},
  27. sync::Mutex,
  28. };
  29. pub use self::constants::*;
  30. mod constants;
  31. pub use self::default::*;
  32. mod default;
  33. pub use self::getdelim::*;
  34. mod getdelim;
  35. mod ext;
  36. mod helpers;
  37. mod lookaheadreader;
  38. mod printf;
  39. mod scanf;
  40. use lookaheadreader::LookAheadReader;
  41. static mut TMPNAM_BUF: [c_char; L_tmpnam as usize + 1] = [0; L_tmpnam as usize + 1];
  42. enum Buffer<'a> {
  43. Borrowed(&'a mut [u8]),
  44. Owned(Vec<u8>),
  45. }
  46. impl<'a> Deref for Buffer<'a> {
  47. type Target = [u8];
  48. fn deref(&self) -> &Self::Target {
  49. match self {
  50. Buffer::Borrowed(inner) => inner,
  51. Buffer::Owned(inner) => inner.borrow(),
  52. }
  53. }
  54. }
  55. impl<'a> DerefMut for Buffer<'a> {
  56. fn deref_mut(&mut self) -> &mut Self::Target {
  57. match self {
  58. Buffer::Borrowed(inner) => inner,
  59. Buffer::Owned(inner) => inner.borrow_mut(),
  60. }
  61. }
  62. }
  63. pub trait Pending {
  64. fn pending(&self) -> size_t;
  65. }
  66. impl<W: core_io::Write> Pending for BufWriter<W> {
  67. fn pending(&self) -> size_t {
  68. self.buf.len() as size_t
  69. }
  70. }
  71. impl<W: core_io::Write> Pending for LineWriter<W> {
  72. fn pending(&self) -> size_t {
  73. self.inner.buf.len() as size_t
  74. }
  75. }
  76. pub trait Writer: Write + Pending {
  77. fn purge(&mut self);
  78. }
  79. impl<W: core_io::Write> Writer for BufWriter<W> {
  80. fn purge(&mut self) {
  81. self.buf.clear();
  82. }
  83. }
  84. impl<W: core_io::Write> Writer for LineWriter<W> {
  85. fn purge(&mut self) {
  86. self.inner.buf.clear();
  87. }
  88. }
  89. /// This struct gets exposed to the C API.
  90. pub struct FILE {
  91. lock: Mutex<()>,
  92. file: File,
  93. // pub for stdio_ext
  94. pub(crate) flags: c_int,
  95. read_buf: Buffer<'static>,
  96. read_pos: usize,
  97. read_size: usize,
  98. unget: Vec<u8>,
  99. // pub for stdio_ext
  100. pub(crate) writer: Box<dyn Writer + Send>,
  101. // Optional pid for use with popen/pclose
  102. pid: Option<c_int>,
  103. // wchar support
  104. pub(crate) orientation: c_int,
  105. }
  106. impl Read for FILE {
  107. fn read(&mut self, out: &mut [u8]) -> io::Result<usize> {
  108. let unget_read_size = cmp::min(out.len(), self.unget.len());
  109. for i in 0..unget_read_size {
  110. out[i] = self.unget.pop().unwrap();
  111. }
  112. if unget_read_size != 0 {
  113. return Ok(unget_read_size);
  114. }
  115. let len = {
  116. let buf = self.fill_buf()?;
  117. let len = buf.len().min(out.len());
  118. out[..len].copy_from_slice(&buf[..len]);
  119. len
  120. };
  121. self.consume(len);
  122. Ok(len)
  123. }
  124. }
  125. impl BufRead for FILE {
  126. fn fill_buf(&mut self) -> io::Result<&[u8]> {
  127. if self.read_pos == self.read_size {
  128. self.read_size = match self.file.read(&mut self.read_buf) {
  129. Ok(0) => {
  130. self.flags |= F_EOF;
  131. 0
  132. }
  133. Ok(n) => n,
  134. Err(err) => {
  135. self.flags |= F_ERR;
  136. return Err(err);
  137. }
  138. };
  139. self.read_pos = 0;
  140. }
  141. Ok(&self.read_buf[self.read_pos..self.read_size])
  142. }
  143. fn consume(&mut self, i: usize) {
  144. self.read_pos = (self.read_pos + i).min(self.read_size);
  145. }
  146. }
  147. impl Write for FILE {
  148. fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
  149. match self.writer.write(buf) {
  150. Ok(n) => Ok(n),
  151. Err(err) => {
  152. self.flags |= F_ERR;
  153. Err(err)
  154. }
  155. }
  156. }
  157. fn flush(&mut self) -> io::Result<()> {
  158. match self.writer.flush() {
  159. Ok(()) => Ok(()),
  160. Err(err) => {
  161. self.flags |= F_ERR;
  162. Err(err)
  163. }
  164. }
  165. }
  166. }
  167. impl WriteFmt for FILE {
  168. fn write_str(&mut self, s: &str) -> fmt::Result {
  169. self.write_all(s.as_bytes())
  170. .map(|_| ())
  171. .map_err(|_| fmt::Error)
  172. }
  173. }
  174. impl WriteByte for FILE {
  175. fn write_u8(&mut self, c: u8) -> fmt::Result {
  176. self.write_all(&[c]).map(|_| ()).map_err(|_| fmt::Error)
  177. }
  178. }
  179. impl FILE {
  180. pub fn lock(&mut self) -> LockGuard {
  181. unsafe {
  182. flockfile(self);
  183. }
  184. LockGuard(self)
  185. }
  186. pub fn try_set_orientation(&mut self, mode: c_int) -> c_int {
  187. let stream = self.lock();
  188. stream.0.try_set_orientation_unlocked(mode)
  189. }
  190. pub fn try_set_orientation_unlocked(&mut self, mode: c_int) -> c_int {
  191. if self.orientation == 0 {
  192. self.orientation = match mode {
  193. 1..=i32::MAX => 1,
  194. i32::MIN..=-1 => -1,
  195. 0 => self.orientation,
  196. };
  197. }
  198. self.orientation
  199. }
  200. pub fn try_set_byte_orientation_unlocked(&mut self) -> core::result::Result<(), c_int> {
  201. match self.try_set_orientation_unlocked(-1) {
  202. i32::MIN..=-1 => Ok(()),
  203. x => Err(x),
  204. }
  205. }
  206. pub fn purge(&mut self) {
  207. // Purge read buffer
  208. self.read_pos = 0;
  209. self.read_size = 0;
  210. // Purge unget
  211. self.unget.clear();
  212. // Purge write buffer
  213. self.writer.purge();
  214. }
  215. }
  216. pub struct LockGuard<'a>(&'a mut FILE);
  217. impl<'a> Deref for LockGuard<'a> {
  218. type Target = FILE;
  219. fn deref(&self) -> &Self::Target {
  220. &self.0
  221. }
  222. }
  223. impl<'a> DerefMut for LockGuard<'a> {
  224. fn deref_mut(&mut self) -> &mut Self::Target {
  225. self.0
  226. }
  227. }
  228. impl<'a> Drop for LockGuard<'a> {
  229. fn drop(&mut self) {
  230. unsafe {
  231. funlockfile(self.0);
  232. }
  233. }
  234. }
  235. /// Clears EOF and ERR indicators on a stream
  236. #[no_mangle]
  237. pub unsafe extern "C" fn clearerr(stream: *mut FILE) {
  238. let mut stream = (*stream).lock();
  239. stream.flags &= !(F_EOF | F_ERR);
  240. }
  241. // #[no_mangle]
  242. pub extern "C" fn ctermid(_s: *mut c_char) -> *mut c_char {
  243. unimplemented!();
  244. }
  245. // #[no_mangle]
  246. pub extern "C" fn cuserid(_s: *mut c_char) -> *mut c_char {
  247. unimplemented!();
  248. }
  249. /// Close a file
  250. /// This function does not guarentee that the file buffer will be flushed or that the file
  251. /// descriptor will be closed, so if it is important that the file be written to, use `fflush()`
  252. /// prior to using this function.
  253. #[no_mangle]
  254. pub unsafe extern "C" fn fclose(stream: *mut FILE) -> c_int {
  255. let stream = &mut *stream;
  256. flockfile(stream);
  257. let mut r = stream.flush().is_err();
  258. let close = Sys::close(*stream.file) < 0;
  259. r = r || close;
  260. if stream.flags & constants::F_PERM == 0 {
  261. // Not one of stdin, stdout or stderr
  262. let mut stream = Box::from_raw(stream);
  263. // Reference files aren't closed on drop, so pretend to be a reference
  264. stream.file.reference = true;
  265. } else {
  266. funlockfile(stream);
  267. }
  268. r as c_int
  269. }
  270. /// Open a file from a file descriptor
  271. #[no_mangle]
  272. pub unsafe extern "C" fn fdopen(fildes: c_int, mode: *const c_char) -> *mut FILE {
  273. if let Some(f) = helpers::_fdopen(fildes, mode) {
  274. f
  275. } else {
  276. ptr::null_mut()
  277. }
  278. }
  279. /// Check for EOF
  280. #[no_mangle]
  281. pub unsafe extern "C" fn feof(stream: *mut FILE) -> c_int {
  282. let stream = (*stream).lock();
  283. stream.flags & F_EOF
  284. }
  285. /// Check for ERR
  286. #[no_mangle]
  287. pub unsafe extern "C" fn ferror(stream: *mut FILE) -> c_int {
  288. let stream = (*stream).lock();
  289. stream.flags & F_ERR
  290. }
  291. /// Flush output to stream, or sync read position
  292. /// Ensure the file is unlocked before calling this function, as it will attempt to lock the file
  293. /// itself.
  294. #[no_mangle]
  295. pub unsafe extern "C" fn fflush(stream: *mut FILE) -> c_int {
  296. if stream.is_null() {
  297. //TODO: flush all files!
  298. if fflush(stdout) != 0 {
  299. return EOF;
  300. }
  301. if fflush(stderr) != 0 {
  302. return EOF;
  303. }
  304. } else {
  305. let mut stream = (*stream).lock();
  306. if stream.flush().is_err() {
  307. return EOF;
  308. }
  309. }
  310. 0
  311. }
  312. /// Get a single char from a stream
  313. #[no_mangle]
  314. pub unsafe extern "C" fn fgetc(stream: *mut FILE) -> c_int {
  315. let mut stream = (*stream).lock();
  316. if let Err(_) = (*stream).try_set_byte_orientation_unlocked() {
  317. return -1;
  318. }
  319. getc_unlocked(&mut *stream)
  320. }
  321. /// Get the position of the stream and store it in pos
  322. #[no_mangle]
  323. pub unsafe extern "C" fn fgetpos(stream: *mut FILE, pos: *mut fpos_t) -> c_int {
  324. let off = ftello(stream);
  325. if off < 0 {
  326. return -1;
  327. }
  328. *pos = off;
  329. 0
  330. }
  331. /// Get a string from the stream
  332. #[no_mangle]
  333. pub unsafe extern "C" fn fgets(
  334. original: *mut c_char,
  335. max: c_int,
  336. stream: *mut FILE,
  337. ) -> *mut c_char {
  338. let mut stream = (*stream).lock();
  339. if let Err(_) = (*stream).try_set_byte_orientation_unlocked() {
  340. return ptr::null_mut();
  341. }
  342. let mut out = original;
  343. let max = max as usize;
  344. let mut left = max.saturating_sub(1); // Make space for the terminating NUL-byte
  345. let mut wrote = false;
  346. if left >= 1 {
  347. let unget_read_size = cmp::min(left, stream.unget.len());
  348. for _ in 0..unget_read_size {
  349. *out = stream.unget.pop().unwrap() as i8;
  350. out = out.offset(1);
  351. }
  352. left -= unget_read_size;
  353. }
  354. loop {
  355. if left == 0 {
  356. break;
  357. }
  358. // TODO: When NLL is a thing, this block can be flattened out
  359. let (read, exit) = {
  360. let buf = match stream.fill_buf() {
  361. Ok(buf) => buf,
  362. Err(_) => return ptr::null_mut(),
  363. };
  364. if buf.is_empty() {
  365. break;
  366. }
  367. wrote = true;
  368. let len = buf.len().min(left);
  369. let newline = buf[..len].iter().position(|&c| c == b'\n');
  370. let len = newline.map(|i| i + 1).unwrap_or(len);
  371. ptr::copy_nonoverlapping(buf.as_ptr(), out as *mut u8, len);
  372. (len, newline.is_some())
  373. };
  374. stream.consume(read);
  375. out = out.add(read);
  376. left -= read;
  377. if exit {
  378. break;
  379. }
  380. }
  381. if max >= 1 {
  382. // Write the NUL byte
  383. *out = 0;
  384. }
  385. if wrote {
  386. original
  387. } else {
  388. ptr::null_mut()
  389. }
  390. }
  391. /// Get the underlying file descriptor
  392. #[no_mangle]
  393. pub unsafe extern "C" fn fileno(stream: *mut FILE) -> c_int {
  394. let stream = (*stream).lock();
  395. *stream.file
  396. }
  397. /// Lock the file
  398. /// Do not call any functions other than those with the `_unlocked` postfix while the file is
  399. /// locked
  400. #[no_mangle]
  401. pub unsafe extern "C" fn flockfile(file: *mut FILE) {
  402. (*file).lock.manual_lock();
  403. }
  404. /// Open the file in mode `mode`
  405. #[no_mangle]
  406. pub unsafe extern "C" fn fopen(filename: *const c_char, mode: *const c_char) -> *mut FILE {
  407. let initial_mode = *mode;
  408. if initial_mode != b'r' as i8 && initial_mode != b'w' as i8 && initial_mode != b'a' as i8 {
  409. platform::errno = errno::EINVAL;
  410. return ptr::null_mut();
  411. }
  412. let flags = helpers::parse_mode_flags(mode);
  413. let new_mode = if flags & fcntl::O_CREAT == fcntl::O_CREAT {
  414. 0o666
  415. } else {
  416. 0
  417. };
  418. let fd = fcntl::sys_open(filename, flags, new_mode);
  419. if fd < 0 {
  420. return ptr::null_mut();
  421. }
  422. if flags & fcntl::O_CLOEXEC > 0 {
  423. fcntl::sys_fcntl(fd, fcntl::F_SETFD, fcntl::FD_CLOEXEC);
  424. }
  425. if let Some(f) = helpers::_fdopen(fd, mode) {
  426. f
  427. } else {
  428. Sys::close(fd);
  429. ptr::null_mut()
  430. }
  431. }
  432. /// Clear the buffers of a stream
  433. /// Ensure the file is unlocked before calling this function, as it will attempt to lock the file
  434. /// itself.
  435. #[no_mangle]
  436. pub unsafe extern "C" fn __fpurge(stream: *mut FILE) {
  437. if ! stream.is_null() {
  438. let mut stream = (*stream).lock();
  439. stream.purge();
  440. }
  441. }
  442. /// Insert a character into the stream
  443. #[no_mangle]
  444. pub unsafe extern "C" fn fputc(c: c_int, stream: *mut FILE) -> c_int {
  445. let mut stream = (*stream).lock();
  446. if let Err(_) = (*stream).try_set_byte_orientation_unlocked() {
  447. return -1;
  448. }
  449. putc_unlocked(c, &mut *stream)
  450. }
  451. /// Insert a string into a stream
  452. #[no_mangle]
  453. pub unsafe extern "C" fn fputs(s: *const c_char, stream: *mut FILE) -> c_int {
  454. let mut stream = (*stream).lock();
  455. if let Err(_) = (*stream).try_set_byte_orientation_unlocked() {
  456. return -1;
  457. }
  458. let buf = slice::from_raw_parts(s as *mut u8, strlen(s));
  459. if stream.write_all(&buf).is_ok() {
  460. 0
  461. } else {
  462. -1
  463. }
  464. }
  465. /// Read `nitems` of size `size` into `ptr` from `stream`
  466. #[no_mangle]
  467. pub unsafe extern "C" fn fread(
  468. ptr: *mut c_void,
  469. size: size_t,
  470. nitems: size_t,
  471. stream: *mut FILE,
  472. ) -> size_t {
  473. if size == 0 || nitems == 0 {
  474. return 0;
  475. }
  476. let mut stream = (*stream).lock();
  477. if let Err(_) = (*stream).try_set_byte_orientation_unlocked() {
  478. return 0;
  479. }
  480. let buf = slice::from_raw_parts_mut(ptr as *mut u8, size as usize * nitems as usize);
  481. let mut read = 0;
  482. while read < buf.len() {
  483. match stream.read(&mut buf[read..]) {
  484. Ok(0) | Err(_) => break,
  485. Ok(n) => read += n,
  486. }
  487. }
  488. (read / size as usize) as size_t
  489. }
  490. #[no_mangle]
  491. pub unsafe extern "C" fn freopen(
  492. filename: *const c_char,
  493. mode: *const c_char,
  494. stream: &mut FILE,
  495. ) -> *mut FILE {
  496. let mut flags = helpers::parse_mode_flags(mode);
  497. flockfile(stream);
  498. let _ = stream.flush();
  499. if filename.is_null() {
  500. // Reopen stream in new mode
  501. if flags & fcntl::O_CLOEXEC > 0 {
  502. fcntl::sys_fcntl(*stream.file, fcntl::F_SETFD, fcntl::FD_CLOEXEC);
  503. }
  504. flags &= !(fcntl::O_CREAT | fcntl::O_EXCL | fcntl::O_CLOEXEC);
  505. if fcntl::sys_fcntl(*stream.file, fcntl::F_SETFL, flags) < 0 {
  506. funlockfile(stream);
  507. fclose(stream);
  508. return ptr::null_mut();
  509. }
  510. } else {
  511. let new = fopen(filename, mode);
  512. if new.is_null() {
  513. funlockfile(stream);
  514. fclose(stream);
  515. return ptr::null_mut();
  516. }
  517. let new = &mut *new; // Should be safe, new is not null
  518. if *new.file == *stream.file {
  519. new.file.fd = -1;
  520. } else if Sys::dup2(*new.file, *stream.file) < 0
  521. || fcntl::sys_fcntl(*stream.file, fcntl::F_SETFL, flags & fcntl::O_CLOEXEC) < 0
  522. {
  523. funlockfile(stream);
  524. fclose(new);
  525. fclose(stream);
  526. return ptr::null_mut();
  527. }
  528. stream.flags = (stream.flags & constants::F_PERM) | new.flags;
  529. fclose(new);
  530. }
  531. stream.orientation = 0;
  532. funlockfile(stream);
  533. stream
  534. }
  535. /// Seek to an offset `offset` from `whence`
  536. #[no_mangle]
  537. pub unsafe extern "C" fn fseek(stream: *mut FILE, offset: c_long, whence: c_int) -> c_int {
  538. fseeko(stream, offset as off_t, whence)
  539. }
  540. /// Seek to an offset `offset` from `whence`
  541. #[no_mangle]
  542. pub unsafe extern "C" fn fseeko(stream: *mut FILE, off: off_t, whence: c_int) -> c_int {
  543. let mut stream = (*stream).lock();
  544. fseek_locked(&mut *stream, off, whence)
  545. }
  546. pub unsafe fn fseek_locked(stream: &mut FILE, mut off: off_t, whence: c_int) -> c_int {
  547. if whence == SEEK_CUR {
  548. // Since it's a buffered writer, our actual cursor isn't where the user
  549. // thinks
  550. off -= (stream.read_size - stream.read_pos) as off_t;
  551. }
  552. // Flush write buffer before seek
  553. if stream.flush().is_err() {
  554. return -1;
  555. }
  556. let err = Sys::lseek(*stream.file, off, whence);
  557. if err < 0 {
  558. return err as c_int;
  559. }
  560. stream.flags &= !(F_EOF | F_ERR);
  561. stream.read_pos = 0;
  562. stream.read_size = 0;
  563. stream.unget = Vec::new();
  564. 0
  565. }
  566. /// Seek to a position `pos` in the file from the beginning of the file
  567. #[no_mangle]
  568. pub unsafe extern "C" fn fsetpos(stream: *mut FILE, pos: *const fpos_t) -> c_int {
  569. fseeko(stream, *pos, SEEK_SET)
  570. }
  571. /// Get the current position of the cursor in the file
  572. #[no_mangle]
  573. pub unsafe extern "C" fn ftell(stream: *mut FILE) -> c_long {
  574. ftello(stream) as c_long
  575. }
  576. /// Get the current position of the cursor in the file
  577. #[no_mangle]
  578. pub unsafe extern "C" fn ftello(stream: *mut FILE) -> off_t {
  579. let mut stream = (*stream).lock();
  580. ftell_locked(&mut *stream)
  581. }
  582. pub unsafe extern "C" fn ftell_locked(stream: &mut FILE) -> off_t {
  583. let pos = Sys::lseek(*stream.file, 0, SEEK_CUR);
  584. if pos < 0 {
  585. return -1;
  586. }
  587. pos - (stream.read_size - stream.read_pos) as off_t - stream.unget.len() as off_t
  588. }
  589. /// Try to lock the file. Returns 0 for success, 1 for failure
  590. #[no_mangle]
  591. pub unsafe extern "C" fn ftrylockfile(file: *mut FILE) -> c_int {
  592. if (*file).lock.manual_try_lock().is_ok() {
  593. 0
  594. } else {
  595. 1
  596. }
  597. }
  598. /// Unlock the file
  599. #[no_mangle]
  600. pub unsafe extern "C" fn funlockfile(file: *mut FILE) {
  601. (*file).lock.manual_unlock();
  602. }
  603. /// Write `nitems` of size `size` from `ptr` to `stream`
  604. #[no_mangle]
  605. pub unsafe extern "C" fn fwrite(
  606. ptr: *const c_void,
  607. size: size_t,
  608. nitems: size_t,
  609. stream: *mut FILE,
  610. ) -> size_t {
  611. if size == 0 || nitems == 0 {
  612. return 0;
  613. }
  614. let mut stream = (*stream).lock();
  615. if let Err(_) = (*stream).try_set_byte_orientation_unlocked() {
  616. return 0;
  617. }
  618. let buf = slice::from_raw_parts(ptr as *const u8, size as usize * nitems as usize);
  619. let mut written = 0;
  620. while written < buf.len() {
  621. match stream.write(&buf[written..]) {
  622. Ok(0) | Err(_) => break,
  623. Ok(n) => written += n,
  624. }
  625. }
  626. (written / size as usize) as size_t
  627. }
  628. /// Get a single char from a stream
  629. #[no_mangle]
  630. pub unsafe extern "C" fn getc(stream: *mut FILE) -> c_int {
  631. let mut stream = (*stream).lock();
  632. getc_unlocked(&mut *stream)
  633. }
  634. /// Get a single char from `stdin`
  635. #[no_mangle]
  636. pub unsafe extern "C" fn getchar() -> c_int {
  637. fgetc(&mut *stdin)
  638. }
  639. /// Get a char from a stream without locking the stream
  640. #[no_mangle]
  641. pub unsafe extern "C" fn getc_unlocked(stream: *mut FILE) -> c_int {
  642. if let Err(_) = (*stream).try_set_byte_orientation_unlocked() {
  643. return -1;
  644. }
  645. let mut buf = [0];
  646. match (*stream).read(&mut buf) {
  647. Ok(0) | Err(_) => EOF,
  648. Ok(_) => buf[0] as c_int,
  649. }
  650. }
  651. /// Get a char from `stdin` without locking `stdin`
  652. #[no_mangle]
  653. pub unsafe extern "C" fn getchar_unlocked() -> c_int {
  654. getc_unlocked(&mut *stdin)
  655. }
  656. /// Get a string from `stdin`
  657. #[no_mangle]
  658. pub unsafe extern "C" fn gets(s: *mut c_char) -> *mut c_char {
  659. fgets(s, c_int::max_value(), &mut *stdin)
  660. }
  661. /// Get an integer from `stream`
  662. #[no_mangle]
  663. pub unsafe extern "C" fn getw(stream: *mut FILE) -> c_int {
  664. let mut ret: c_int = 0;
  665. if fread(
  666. &mut ret as *mut _ as *mut c_void,
  667. mem::size_of_val(&ret),
  668. 1,
  669. stream,
  670. ) > 0
  671. {
  672. ret
  673. } else {
  674. -1
  675. }
  676. }
  677. #[no_mangle]
  678. pub unsafe extern "C" fn pclose(stream: *mut FILE) -> c_int {
  679. let pid = {
  680. let mut stream = (*stream).lock();
  681. if let Some(pid) = stream.pid.take() {
  682. pid
  683. } else {
  684. errno = errno::ECHILD;
  685. return -1;
  686. }
  687. };
  688. fclose(stream);
  689. let mut wstatus = 0;
  690. if Sys::waitpid(pid, &mut wstatus, 0) < 0 {
  691. return -1;
  692. }
  693. wstatus
  694. }
  695. #[no_mangle]
  696. pub unsafe extern "C" fn perror(s: *const c_char) {
  697. let s_cstr = CStr::from_ptr(s);
  698. let s_str = str::from_utf8_unchecked(s_cstr.to_bytes());
  699. let mut w = platform::FileWriter(2);
  700. if errno >= 0 && errno < STR_ERROR.len() as c_int {
  701. w.write_fmt(format_args!("{}: {}\n", s_str, STR_ERROR[errno as usize]))
  702. .unwrap();
  703. } else {
  704. w.write_fmt(format_args!("{}: Unknown error {}\n", s_str, errno))
  705. .unwrap();
  706. }
  707. }
  708. #[no_mangle]
  709. pub unsafe extern "C" fn popen(command: *const c_char, mode: *const c_char) -> *mut FILE {
  710. //TODO: share code with system
  711. let mode = CStr::from_ptr(mode);
  712. let mut cloexec = false;
  713. let mut write_opt = None;
  714. for b in mode.to_bytes().iter() {
  715. match b {
  716. b'e' => cloexec = true,
  717. b'r' if write_opt.is_none() => write_opt = Some(false),
  718. b'w' if write_opt.is_none() => write_opt = Some(true),
  719. _ => {
  720. errno = errno::EINVAL;
  721. return ptr::null_mut();
  722. }
  723. }
  724. }
  725. let write = match write_opt {
  726. Some(some) => some,
  727. None => {
  728. errno = errno::EINVAL;
  729. return ptr::null_mut();
  730. }
  731. };
  732. let mut pipes = [-1, -1];
  733. if unistd::pipe(pipes.as_mut_ptr()) != 0 {
  734. return ptr::null_mut();
  735. }
  736. let child_pid = unistd::fork();
  737. if child_pid == 0 {
  738. let command_nonnull = if command.is_null() {
  739. "exit 0\0".as_ptr()
  740. } else {
  741. command as *const u8
  742. };
  743. let shell = "/bin/sh\0".as_ptr();
  744. let args = [
  745. "sh\0".as_ptr(),
  746. "-c\0".as_ptr(),
  747. command_nonnull,
  748. ptr::null(),
  749. ];
  750. // Setup up stdin or stdout
  751. //TODO: dup errors are ignored, should they be?
  752. {
  753. if write {
  754. unistd::dup2(0, pipes[0]);
  755. } else {
  756. unistd::dup2(1, pipes[1]);
  757. }
  758. unistd::close(pipes[0]);
  759. unistd::close(pipes[1]);
  760. }
  761. unistd::execv(shell as *const c_char, args.as_ptr() as *const *mut c_char);
  762. stdlib::exit(127);
  763. unreachable!();
  764. } else if child_pid > 0 {
  765. let (fd, fd_mode) = if write {
  766. unistd::close(pipes[0]);
  767. (pipes[1], if cloexec { c_str!("we") } else { c_str!("w") })
  768. } else {
  769. unistd::close(pipes[1]);
  770. (pipes[0], if cloexec { c_str!("re") } else { c_str!("r") })
  771. };
  772. if let Some(f) = helpers::_fdopen(fd, fd_mode.as_ptr()) {
  773. (*f).pid = Some(child_pid);
  774. f
  775. } else {
  776. ptr::null_mut()
  777. }
  778. } else {
  779. ptr::null_mut()
  780. }
  781. }
  782. /// Put a character `c` into `stream`
  783. #[no_mangle]
  784. pub unsafe extern "C" fn putc(c: c_int, stream: *mut FILE) -> c_int {
  785. let mut stream = (*stream).lock();
  786. putc_unlocked(c, &mut *stream)
  787. }
  788. /// Put a character `c` into `stdout`
  789. #[no_mangle]
  790. pub unsafe extern "C" fn putchar(c: c_int) -> c_int {
  791. fputc(c, &mut *stdout)
  792. }
  793. /// Put a character `c` into `stream` without locking `stream`
  794. #[no_mangle]
  795. pub unsafe extern "C" fn putc_unlocked(c: c_int, stream: *mut FILE) -> c_int {
  796. if let Err(_) = (*stream).try_set_byte_orientation_unlocked() {
  797. return -1;
  798. }
  799. match (*stream).write(&[c as u8]) {
  800. Ok(0) | Err(_) => EOF,
  801. Ok(_) => c,
  802. }
  803. }
  804. /// Put a character `c` into `stdout` without locking `stdout`
  805. #[no_mangle]
  806. pub unsafe extern "C" fn putchar_unlocked(c: c_int) -> c_int {
  807. putc_unlocked(c, stdout)
  808. }
  809. /// Put a string `s` into `stdout`
  810. #[no_mangle]
  811. pub unsafe extern "C" fn puts(s: *const c_char) -> c_int {
  812. let mut stream = (&mut *stdout).lock();
  813. if let Err(_) = (*stream).try_set_byte_orientation_unlocked() {
  814. return -1;
  815. }
  816. let buf = slice::from_raw_parts(s as *mut u8, strlen(s));
  817. if stream.write_all(&buf).is_err() {
  818. return -1;
  819. }
  820. if stream.write(&[b'\n']).is_err() {
  821. return -1;
  822. }
  823. 0
  824. }
  825. /// Put an integer `w` into `stream`
  826. #[no_mangle]
  827. pub unsafe extern "C" fn putw(w: c_int, stream: *mut FILE) -> c_int {
  828. fwrite(&w as *const c_int as _, mem::size_of_val(&w), 1, stream) as i32 - 1
  829. }
  830. /// Delete file or directory `path`
  831. #[no_mangle]
  832. pub unsafe extern "C" fn remove(path: *const c_char) -> c_int {
  833. let path = CStr::from_ptr(path);
  834. let r = Sys::unlink(path);
  835. if r == -errno::EISDIR {
  836. Sys::rmdir(path)
  837. } else {
  838. r
  839. }
  840. }
  841. #[no_mangle]
  842. pub unsafe extern "C" fn rename(oldpath: *const c_char, newpath: *const c_char) -> c_int {
  843. let oldpath = CStr::from_ptr(oldpath);
  844. let newpath = CStr::from_ptr(newpath);
  845. Sys::rename(oldpath, newpath)
  846. }
  847. /// Rewind `stream` back to the beginning of it
  848. #[no_mangle]
  849. pub unsafe extern "C" fn rewind(stream: *mut FILE) {
  850. fseeko(stream, 0, SEEK_SET);
  851. }
  852. /// Reset `stream` to use buffer `buf`. Buffer must be `BUFSIZ` in length
  853. #[no_mangle]
  854. pub unsafe extern "C" fn setbuf(stream: *mut FILE, buf: *mut c_char) {
  855. setvbuf(
  856. stream,
  857. buf,
  858. if buf.is_null() { _IONBF } else { _IOFBF },
  859. BUFSIZ as usize,
  860. );
  861. }
  862. /// Reset `stream` to use buffer `buf` of size `size`
  863. /// If this isn't the meaning of unsafe, idk what is
  864. #[no_mangle]
  865. pub unsafe extern "C" fn setvbuf(
  866. stream: *mut FILE,
  867. buf: *mut c_char,
  868. mode: c_int,
  869. mut size: size_t,
  870. ) -> c_int {
  871. let mut stream = (*stream).lock();
  872. // Set a buffer of size `size` if no buffer is given
  873. stream.read_buf = if buf.is_null() || size == 0 {
  874. if size == 0 {
  875. size = BUFSIZ as usize;
  876. }
  877. // TODO: Make it unbuffered if _IONBF
  878. // if mode == _IONBF {
  879. // } else {
  880. Buffer::Owned(vec![0; size as usize])
  881. // }
  882. } else {
  883. Buffer::Borrowed(slice::from_raw_parts_mut(buf as *mut u8, size))
  884. };
  885. stream.flags |= F_SVB;
  886. 0
  887. }
  888. #[no_mangle]
  889. pub unsafe extern "C" fn tempnam(dir: *const c_char, pfx: *const c_char) -> *mut c_char {
  890. unsafe fn is_appropriate(pos_dir: *const c_char) -> bool {
  891. !pos_dir.is_null() && unistd::access(pos_dir, unistd::W_OK) == 0
  892. }
  893. // directory search order is env!(TMPDIR), dir, P_tmpdir, "/tmp"
  894. let dirname = {
  895. let tmpdir = stdlib::getenv(b"TMPDIR\0".as_ptr() as _);
  896. [tmpdir, dir, P_tmpdir.as_ptr() as _]
  897. .iter()
  898. .copied()
  899. .skip_while(|&d| !is_appropriate(d))
  900. .next()
  901. .unwrap_or(b"/tmp\0".as_ptr() as _)
  902. };
  903. let dirname_len = string::strlen(dirname);
  904. let prefix_len = string::strnlen_s(pfx, 5);
  905. // allocate enough for dirname "/" prefix "XXXXXX\0"
  906. let mut out_buf =
  907. platform::alloc(dirname_len + 1 + prefix_len + L_tmpnam as usize + 1) as *mut c_char;
  908. if !out_buf.is_null() {
  909. // copy the directory name and prefix into the allocated buffer
  910. out_buf.copy_from_nonoverlapping(dirname, dirname_len);
  911. *out_buf.add(dirname_len) = b'/' as _;
  912. out_buf
  913. .add(dirname_len + 1)
  914. .copy_from_nonoverlapping(pfx, prefix_len);
  915. // use the same mechanism as tmpnam to get the file name
  916. if tmpnam_inner(out_buf, dirname_len + 1 + prefix_len).is_null() {
  917. // failed to find a valid file name, so we need to free the buffer
  918. platform::free(out_buf as _);
  919. out_buf = ptr::null_mut();
  920. }
  921. }
  922. out_buf
  923. }
  924. #[no_mangle]
  925. pub unsafe extern "C" fn tmpfile() -> *mut FILE {
  926. let mut file_name = *b"/tmp/tmpfileXXXXXX\0";
  927. let file_name = file_name.as_mut_ptr() as *mut c_char;
  928. let fd = stdlib::mkstemp(file_name);
  929. if fd < 0 {
  930. return ptr::null_mut();
  931. }
  932. let fp = fdopen(fd, c_str!("w+").as_ptr());
  933. {
  934. let file_name = CStr::from_ptr(file_name);
  935. Sys::unlink(file_name);
  936. }
  937. if fp.is_null() {
  938. Sys::close(fd);
  939. }
  940. fp
  941. }
  942. #[no_mangle]
  943. pub unsafe extern "C" fn tmpnam(s: *mut c_char) -> *mut c_char {
  944. let buf = if s.is_null() {
  945. TMPNAM_BUF.as_mut_ptr()
  946. } else {
  947. s
  948. };
  949. *buf = b'/' as _;
  950. tmpnam_inner(buf, 1)
  951. }
  952. unsafe extern "C" fn tmpnam_inner(buf: *mut c_char, offset: usize) -> *mut c_char {
  953. const TEMPLATE: &[u8] = b"XXXXXX\0";
  954. buf.add(offset)
  955. .copy_from_nonoverlapping(TEMPLATE.as_ptr() as _, TEMPLATE.len());
  956. let err = platform::errno;
  957. stdlib::mktemp(buf);
  958. platform::errno = err;
  959. if *buf == 0 {
  960. ptr::null_mut()
  961. } else {
  962. buf
  963. }
  964. }
  965. /// Push character `c` back onto `stream` so it'll be read next
  966. #[no_mangle]
  967. pub unsafe extern "C" fn ungetc(c: c_int, stream: *mut FILE) -> c_int {
  968. let mut stream = (*stream).lock();
  969. if let Err(_) = (*stream).try_set_byte_orientation_unlocked() {
  970. return -1;
  971. }
  972. stream.unget.push(c as u8);
  973. c
  974. }
  975. #[no_mangle]
  976. pub unsafe extern "C" fn vfprintf(file: *mut FILE, format: *const c_char, ap: va_list) -> c_int {
  977. let mut file = (*file).lock();
  978. if let Err(_) = file.try_set_byte_orientation_unlocked() {
  979. return -1;
  980. }
  981. printf::printf(&mut *file, format, ap)
  982. }
  983. #[no_mangle]
  984. pub unsafe extern "C" fn vprintf(format: *const c_char, ap: va_list) -> c_int {
  985. vfprintf(&mut *stdout, format, ap)
  986. }
  987. #[no_mangle]
  988. pub unsafe extern "C" fn vasprintf(
  989. strp: *mut *mut c_char,
  990. format: *const c_char,
  991. ap: va_list,
  992. ) -> c_int {
  993. let mut alloc_writer = CVec::new();
  994. let ret = printf::printf(&mut alloc_writer, format, ap);
  995. alloc_writer.push(0).unwrap();
  996. alloc_writer.shrink_to_fit().unwrap();
  997. *strp = alloc_writer.leak() as *mut c_char;
  998. ret
  999. }
  1000. #[no_mangle]
  1001. pub unsafe extern "C" fn vsnprintf(
  1002. s: *mut c_char,
  1003. n: size_t,
  1004. format: *const c_char,
  1005. ap: va_list,
  1006. ) -> c_int {
  1007. printf::printf(
  1008. &mut platform::StringWriter(s as *mut u8, n as usize),
  1009. format,
  1010. ap,
  1011. )
  1012. }
  1013. #[no_mangle]
  1014. pub unsafe extern "C" fn vsprintf(s: *mut c_char, format: *const c_char, ap: va_list) -> c_int {
  1015. printf::printf(&mut platform::UnsafeStringWriter(s as *mut u8), format, ap)
  1016. }
  1017. #[no_mangle]
  1018. pub unsafe extern "C" fn vfscanf(file: *mut FILE, format: *const c_char, ap: va_list) -> c_int {
  1019. let ret = {
  1020. let mut file = (*file).lock();
  1021. if let Err(_) = file.try_set_byte_orientation_unlocked() {
  1022. return -1;
  1023. }
  1024. let f: &mut FILE = &mut *file;
  1025. let reader: LookAheadReader = f.into();
  1026. scanf::scanf(reader, format, ap)
  1027. };
  1028. ret
  1029. }
  1030. #[no_mangle]
  1031. pub unsafe extern "C" fn vscanf(format: *const c_char, ap: va_list) -> c_int {
  1032. vfscanf(&mut *stdin, format, ap)
  1033. }
  1034. #[no_mangle]
  1035. pub unsafe extern "C" fn vsscanf(s: *const c_char, format: *const c_char, ap: va_list) -> c_int {
  1036. let reader = (s as *const u8).into();
  1037. scanf::scanf(reader, format, ap)
  1038. }
  1039. pub unsafe fn flush_io_streams() {
  1040. let flush = |stream: *mut FILE| {
  1041. let stream = &mut *stream;
  1042. stream.flush()
  1043. };
  1044. flush(stdout);
  1045. flush(stderr);
  1046. }