Newer
Older
//! stdio implementation for Redox, following http://pubs.opengroup.org/onlinepubs/7908799/xsh/stdio.h.html
use alloc::borrow::{Borrow, BorrowMut};
use alloc::boxed::Box;
use core::fmt::Write as WriteFmt;
use core::ops::{Deref, DerefMut};
use core::sync::atomic::{self, AtomicBool, Ordering};
use header::errno::{self, STR_ERROR};
use platform::{errno, WriteByte};
use platform;
enum Buffer<'a> {
Borrowed(&'a mut [u8]),
Owned(Vec<u8>)
Tom Almeida
committed
}
impl<'a> Deref for Buffer<'a> {
type Target = [u8];
Tom Almeida
committed
fn deref(&self) -> &Self::Target {
match self {
Buffer::Borrowed(inner) => inner,
Buffer::Owned(inner) => inner.borrow()
Tom Almeida
committed
}
}
}
impl<'a> DerefMut for Buffer<'a> {
fn deref_mut(&mut self) -> &mut Self::Target {
match self {
Buffer::Borrowed(inner) => inner,
Buffer::Owned(inner) => inner.borrow_mut()
Tom Almeida
committed
}
Tom Almeida
committed
/// This struct gets exposed to the C API.
pub struct FILE {
// Can't use spin crate because *_unlocked functions are things in C :(
lock: AtomicBool,
file: File,
flags: c_int,
read_buf: Buffer<'static>,
read_pos: usize,
read_size: usize,
unget: Option<u8>,
writer: LineWriter<File>
}
impl Read for FILE {
fn read(&mut self, out: &mut [u8]) -> io::Result<usize> {
if !out.is_empty() {
Tom Almeida
committed
}
}
let len = {
let buf = self.fill_buf()?;
let len = buf.len().min(out.len());
self.consume(len);
Ok(len)
}
}
impl BufRead for FILE {
fn fill_buf(&mut self) -> io::Result<&[u8]> {
if self.read_pos == self.read_size {
self.read_size = self.file.read(&mut self.read_buf)?;
self.read_pos = 0;
Ok(&self.read_buf[self.read_pos..self.read_size])
Tom Almeida
committed
}
fn consume(&mut self, i: usize) {
self.read_pos = (self.read_pos + i).min(self.read_size);
Tom Almeida
committed
}
}
impl Write for FILE {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.writer.write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.writer.flush()
}
}
impl WriteFmt for FILE {
fn write_str(&mut self, s: &str) -> fmt::Result {
self.write_all(s.as_bytes())
.map(|_| ())
.map_err(|_| fmt::Error)
}
}
impl WriteByte for FILE {
fn write_u8(&mut self, c: u8) -> fmt::Result {
self.write_all(&[c])
.map(|_| ())
.map_err(|_| fmt::Error)
}
}
impl FILE {
pub fn lock(&mut self) -> LockGuard {
flockfile(self);
LockGuard(self)
}
}
pub struct LockGuard<'a>(&'a mut FILE);
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<'a> DerefMut for LockGuard<'a> {
fn deref_mut(&mut self) -> &mut Self::Target {
impl<'a> Drop for LockGuard<'a> {
fn drop(&mut self) {
funlockfile(self.0);
}
Tom Almeida
committed
}
Tom Almeida
committed
pub extern "C" fn clearerr(stream: &mut FILE) {
Tom Almeida
committed
pub extern "C" fn ctermid(_s: *mut c_char) -> *mut c_char {
Tom Almeida
committed
pub extern "C" fn cuserid(_s: *mut c_char) -> *mut c_char {
/// Close a file
/// This function does not guarentee that the file buffer will be flushed or that the file
/// descriptor will be closed, so if it is important that the file be written to, use `fflush()`
/// prior to using this function.
pub extern "C" fn fclose(stream: *mut FILE) -> c_int {
let stream = unsafe { &mut *stream };
let mut r = stream.flush().is_err();
let close = Sys::close(*stream.file) < 0;
r = r || close;
Tom Almeida
committed
if stream.flags & constants::F_PERM == 0 {
let mut stream = unsafe { Box::from_raw(stream) };
// Reference files aren't closed on drop, so pretend to be a reference
stream.file.reference = true;
Tom Almeida
committed
} else {
funlockfile(stream);
Tom Almeida
committed
pub extern "C" fn fdopen(fildes: c_int, mode: *const c_char) -> *mut FILE {
Tom Almeida
committed
use core::ptr;
Tom Almeida
committed
if let Some(f) = unsafe { helpers::_fdopen(fildes, mode) } {
f
Tom Almeida
committed
} else {
ptr::null_mut()
}
pub extern "C" fn feof(stream: *mut FILE) -> c_int {
let stream = unsafe { &mut *stream }.lock();
pub extern "C" fn ferror(stream: *mut FILE) -> c_int {
let stream = unsafe { &mut *stream }.lock();
/// Flush output to stream, or sync read position
/// Ensure the file is unlocked before calling this function, as it will attempt to lock the file
/// itself.
pub unsafe extern "C" fn fflush(stream: *mut FILE) -> c_int {
unsafe { &mut *stream }.lock().flush().is_err() as c_int
pub extern "C" fn fgetc(stream: *mut FILE) -> c_int {
let mut stream = unsafe { &mut *stream }.lock();
getc_unlocked(&mut *stream)
/// Get the position of the stream and store it in pos
#[no_mangle]
pub extern "C" fn fgetpos(stream: *mut FILE, pos: *mut fpos_t) -> c_int {
let off = ftello(stream);
if off < 0 {
return -1;
}
unsafe {
*pos = off;
}
0
}
/// Get a string from the stream
#[no_mangle]
pub extern "C" fn fgets(original: *mut c_char, max: c_int, stream: *mut FILE) -> *mut c_char {
let mut stream = unsafe { &mut *stream }.lock();
let mut out = original;
let max = max as usize;
let mut left = max.saturating_sub(1); // Make space for the terminating NUL-byte
let mut wrote = false;
Tom Almeida
committed
if left >= 1 {
if let Some(c) = stream.unget.take() {
unsafe {
*out = c as c_char;
out = out.offset(1);
}
left -= 1;
Tom Almeida
committed
}
Tom Almeida
committed
// TODO: When NLL is a thing, this block can be flattened out
let (read, exit) = {
let mut buf = match stream.fill_buf() {
Ok(buf) => buf,
wrote = true;
let len = buf.len().min(left);
let newline = buf[..len].iter().position(|&c| c == b'\n');
let len = newline.map(|i| i + 1).unwrap_or(len);
unsafe {
ptr::copy_nonoverlapping(buf.as_ptr(), out as *mut u8, len);
}
(len, newline.is_some())
};
stream.consume(read);
out = unsafe { out.offset(read as isize) };
left -= read;
if exit {
break;
Tom Almeida
committed
if max >= 1 {
// Write the NUL byte
unsafe {
*out = 0;
}
}
if wrote {
original
} else {
ptr::null_mut()
}
pub extern "C" fn fileno(stream: *mut FILE) -> c_int {
let stream = unsafe { &mut *stream }.lock();
*stream.file
/// Lock the file
/// Do not call any functions other than those with the `_unlocked` postfix while the file is
/// locked
pub extern "C" fn flockfile(file: *mut FILE) {
while ftrylockfile(file) != 0 {
atomic::spin_loop_hint();
}
Tom Almeida
committed
pub extern "C" fn fopen(filename: *const c_char, mode: *const c_char) -> *mut FILE {
Tom Almeida
committed
let initial_mode = unsafe { *mode };
if initial_mode != b'r' as i8 && initial_mode != b'w' as i8 && initial_mode != b'a' as i8 {
Tom Almeida
committed
unsafe { platform::errno = errno::EINVAL };
Tom Almeida
committed
let flags = unsafe { helpers::parse_mode_flags(mode) };
let new_mode = if flags & fcntl::O_CREAT == fcntl::O_CREAT {
0o666
} else {
0
};
let fd = fcntl::sys_open(filename, flags, new_mode);
if fd < 0 {
return ptr::null_mut();
}
if flags & fcntl::O_CLOEXEC > 0 {
fcntl::sys_fcntl(fd, fcntl::F_SETFD, fcntl::FD_CLOEXEC);
}
Tom Almeida
committed
if let Some(f) = unsafe { helpers::_fdopen(fd, mode) } {
f
Tom Almeida
committed
} else {
Tom Almeida
committed
ptr::null_mut()
pub extern "C" fn fputc(c: c_int, stream: *mut FILE) -> c_int {
let mut stream = unsafe { &mut *stream }.lock();
putc_unlocked(c, &mut *stream)
pub extern "C" fn fputs(s: *const c_char, stream: *mut FILE) -> c_int {
Tom Almeida
committed
let len = unsafe { strlen(s) };
(fwrite(s as *const c_void, 1, len, stream) == len) as c_int - 1
/// Read `nitems` of size `size` into `ptr` from `stream`
pub extern "C" fn fread(ptr: *mut c_void, size: size_t, count: size_t, stream: *mut FILE) -> size_t {
let mut stream = unsafe { &mut *stream }.lock();
let buf = unsafe { slice::from_raw_parts_mut(
ptr as *mut u8,
size as usize * count as usize
) };
match stream.read(buf) {
Ok(bytes) => (bytes as usize / size as usize) as size_t,
Tom Almeida
committed
}
Tom Almeida
committed
pub extern "C" fn freopen(
filename: *const c_char,
mode: *const c_char,
Tom Almeida
committed
stream: &mut FILE,
Tom Almeida
committed
let mut flags = unsafe { helpers::parse_mode_flags(mode) };
if filename.is_null() {
// Reopen stream in new mode
fcntl::sys_fcntl(*stream.file, fcntl::F_SETFD, fcntl::FD_CLOEXEC);
}
flags &= !(fcntl::O_CREAT | fcntl::O_EXCL | fcntl::O_CLOEXEC);
if fcntl::sys_fcntl(*stream.file, fcntl::F_SETFL, flags) < 0 {
fclose(stream);
return ptr::null_mut();
}
} else {
Tom Almeida
committed
let new = fopen(filename, mode);
fclose(stream);
return ptr::null_mut();
}
Tom Almeida
committed
let new = unsafe { &mut *new }; // Should be safe, new is not null
if *new.file == *stream.file {
new.file.fd = -1;
} else if Sys::dup2(*new.file, *stream.file) < 0
|| fcntl::sys_fcntl(*stream.file, fcntl::F_SETFL, flags & fcntl::O_CLOEXEC) < 0
fclose(new);
fclose(stream);
return ptr::null_mut();
}
Tom Almeida
committed
stream.flags = (stream.flags & constants::F_PERM) | new.flags;
pub extern "C" fn fseek(stream: *mut FILE, offset: c_long, whence: c_int) -> c_int {
fseeko(stream, offset as off_t, whence)
pub extern "C" fn fseeko(stream: *mut FILE, mut off: off_t, whence: c_int) -> c_int {
let mut stream = unsafe { &mut *stream }.lock();
// Since it's a buffered writer, our actual cursor isn't where the user
// thinks
off -= (stream.read_size - stream.read_pos) as off_t;
Tom Almeida
committed
}
let err = Sys::lseek(*stream.file, off, whence);
if err < 0 {
return err as c_int;
Tom Almeida
committed
stream.flags &= !F_EOF;
stream.read_pos = 0;
stream.read_size = 0;
stream.unget = None;
/// Seek to a position `pos` in the file from the beginning of the file
pub unsafe extern "C" fn fsetpos(stream: *mut FILE, pos: *const fpos_t) -> c_int {
fseek(stream, *pos, SEEK_SET)
/// Get the current position of the cursor in the file
pub extern "C" fn ftell(stream: *mut FILE) -> c_long {
/// Get the current position of the cursor in the file
#[no_mangle]
pub extern "C" fn ftello(stream: *mut FILE) -> off_t {
let mut stream = unsafe { &mut *stream }.lock();
let pos = Sys::lseek(*stream.file, 0, SEEK_CUR);
if pos < 0 {
return -1;
}
pos - (stream.read_size - stream.read_pos) as off_t
/// Try to lock the file. Returns 0 for success, 1 for failure
pub extern "C" fn ftrylockfile(file: *mut FILE) -> c_int {
unsafe { &mut *file }.lock.compare_and_swap(false, true, Ordering::Acquire) as c_int
pub extern "C" fn funlockfile(file: *mut FILE) {
unsafe { &mut *file }.lock.store(false, Ordering::Release);
/// Write `nitems` of size `size` from `ptr` to `stream`
pub extern "C" fn fwrite(ptr: *const c_void, size: usize, count: usize, stream: *mut FILE) -> usize {
let mut stream = unsafe { &mut *stream }.lock();
let buf = unsafe { slice::from_raw_parts_mut(
ptr as *mut u8,
size as usize * count as usize
) };
match stream.write(buf) {
Ok(bytes) => (bytes as usize / size as usize) as size_t,
pub extern "C" fn getc(stream: *mut FILE) -> c_int {
let mut stream = unsafe { &mut *stream }.lock();
getc_unlocked(&mut *stream)
Tom Almeida
committed
pub extern "C" fn getchar() -> c_int {
/// Get a char from a stream without locking the stream
pub extern "C" fn getc_unlocked(stream: *mut FILE) -> c_int {
let mut buf = [0];
match unsafe { &mut *stream }.read(&mut buf) {
Ok(0) | Err(_) => EOF,
Ok(_) => buf[0] as c_int
/// Get a char from `stdin` without locking `stdin`
Tom Almeida
committed
pub extern "C" fn getchar_unlocked() -> c_int {
Tom Almeida
committed
pub extern "C" fn gets(s: *mut c_char) -> *mut c_char {
fgets(s, c_int::max_value(), unsafe { &mut *stdin })
pub extern "C" fn getw(stream: *mut FILE) -> c_int {
use core::mem;
let mut ret: c_int = 0;
if fread(
pub extern "C" fn pclose(_stream: *mut FILE) -> c_int {
let s_cstr = CStr::from_ptr(s);
let s_str = str::from_utf8_unchecked(s_cstr.to_bytes());
if errno >= 0 && errno < STR_ERROR.len() as c_int {
Tom Almeida
committed
w.write_fmt(format_args!("{}: {}\n", s_str, STR_ERROR[errno as usize]))
.unwrap();
Tom Almeida
committed
w.write_fmt(format_args!("{}: Unknown error {}\n", s_str, errno))
.unwrap();
Tom Almeida
committed
pub extern "C" fn popen(_command: *const c_char, _mode: *const c_char) -> *mut FILE {
pub extern "C" fn putc(c: c_int, stream: *mut FILE) -> c_int {
let mut stream = unsafe { &mut *stream }.lock();
putc_unlocked(c, &mut *stream)
Tom Almeida
committed
pub extern "C" fn putchar(c: c_int) -> c_int {
/// Put a character `c` into `stream` without locking `stream`
pub extern "C" fn putc_unlocked(c: c_int, stream: *mut FILE) -> c_int {
match unsafe { &mut *stream }.write(&[c as u8]) {
/// Put a character `c` into `stdout` without locking `stdout`
Tom Almeida
committed
pub extern "C" fn putchar_unlocked(c: c_int) -> c_int {
Tom Almeida
committed
pub extern "C" fn puts(s: *const c_char) -> c_int {
let ret = (fputs(s, unsafe { stdout }) > 0) || (putchar_unlocked(b'\n' as c_int) > 0);
pub extern "C" fn putw(w: c_int, stream: *mut FILE) -> c_int {
fwrite(&w as *const c_int as _, mem::size_of_val(&w), 1, stream) as i32 - 1
pub extern "C" fn remove(path: *const c_char) -> c_int {
let path = unsafe { CStr::from_ptr(path) };
pub extern "C" fn rename(oldpath: *const c_char, newpath: *const c_char) -> c_int {
let oldpath = unsafe { CStr::from_ptr(oldpath) };
let newpath = unsafe { CStr::from_ptr(newpath) };
/// Rewind `stream` back to the beginning of it
pub extern "C" fn rewind(stream: *mut FILE) {
/// Reset `stream` to use buffer `buf`. Buffer must be `BUFSIZ` in length
pub extern "C" fn setbuf(stream: *mut FILE, buf: *mut c_char) {
Tom Almeida
committed
setvbuf(
stream,
buf,
if buf.is_null() { _IONBF } else { _IOFBF },
BUFSIZ as usize,
);
/// Reset `stream` to use buffer `buf` of size `size`
Tom Almeida
committed
/// If this isn't the meaning of unsafe, idk what is
pub extern "C" fn setvbuf(stream: *mut FILE, buf: *mut c_char, mode: c_int, mut size: size_t) -> c_int {
let mut stream = unsafe { &mut *stream }.lock();
Tom Almeida
committed
// Set a buffer of size `size` if no buffer is given
stream.read_buf = if buf.is_null() || size == 0 {
if size == 0 {
}
// TODO: Make it unbuffered if _IONBF
// if mode == _IONBF {
// } else {
Buffer::Owned(vec![0; size as usize])
// }
Tom Almeida
committed
} else {
unsafe {
Buffer::Borrowed(slice::from_raw_parts_mut(
buf as *mut u8,
size
))
}
Tom Almeida
committed
};
stream.flags |= F_SVB;
Tom Almeida
committed
pub extern "C" fn tempnam(_dir: *const c_char, _pfx: *const c_char) -> *mut c_char {
let file_name = file_name.as_mut_ptr() as *mut c_char;
if fd < 0 {
return ptr::null_mut();
}
let fp = fdopen(fd, b"w+".as_ptr() as *const i8);
{
let file_name = unsafe { CStr::from_ptr(file_name) };
Sys::unlink(file_name);
}
Tom Almeida
committed
pub extern "C" fn tmpnam(_s: *mut c_char) -> *mut c_char {
/// Push character `c` back onto `stream` so it'll be read next
pub extern "C" fn ungetc(c: c_int, stream: *mut FILE) -> c_int {
let mut stream = unsafe { &mut *stream }.lock();
if stream.unget.is_some() {
unsafe {
platform::errno = errno::EIO;
return EOF;
Tom Almeida
committed
}
pub unsafe extern "C" fn vfprintf(file: *mut FILE, format: *const c_char, ap: va_list) -> c_int {
let mut file = (*file).lock();
printf::printf(&mut *file, format, ap)
}
#[no_mangle]
pub unsafe extern "C" fn vprintf(format: *const c_char, ap: va_list) -> c_int {
pub unsafe extern "C" fn vsnprintf(
s: *mut c_char,
n: usize,
format: *const c_char,
ap: va_list,
) -> c_int {
Tom Almeida
committed
printf::printf(
&mut platform::StringWriter(s as *mut u8, n as usize),
format,
ap,
)
pub unsafe extern "C" fn vsprintf(s: *mut c_char, format: *const c_char, ap: va_list) -> c_int {
Tom Almeida
committed
printf::printf(&mut platform::UnsafeStringWriter(s as *mut u8), format, ap)
pub unsafe extern "C" fn vfscanf(file: *mut FILE, format: *const c_char, ap: va_list) -> c_int {
let mut file = (*file).lock();
scanf::scanf(&mut *file, format, ap)
}
#[no_mangle]
pub unsafe extern "C" fn vscanf(format: *const c_char, ap: va_list) -> c_int {
}
#[no_mangle]
pub unsafe extern "C" fn vsscanf(s: *const c_char, format: *const c_char, ap: va_list) -> c_int {
scanf::scanf(
&mut platform::UnsafeStringReader(s as *const u8),
format,
ap,
)