Large reorganization of headers (WIP)

This commit is contained in:
Jeremy Soller
2018-08-26 08:11:35 -06:00
parent ff32c8cbbd
commit c20ce5ffed
261 changed files with 236 additions and 1672 deletions
+11
View File
@@ -0,0 +1,11 @@
sys_includes = ["stdarg.h", "stddef.h", "stdint.h", "sys/types.h"]
include_guard = "_STDIO_H"
trailer = "#include <bits/stdio.h>"
language = "C"
style = "Type"
[enum]
prefix_with_name = true
[export.rename]
"AtomicBool" = "volatile char"
+27
View File
@@ -0,0 +1,27 @@
use platform::types::*;
pub const BUFSIZ: size_t = 1024;
pub const UNGET: size_t = 8;
pub const FILENAME_MAX: c_int = 4096;
pub const F_PERM: c_int = 1;
pub const F_NORD: c_int = 4;
pub const F_NOWR: c_int = 8;
pub const F_EOF: c_int = 16;
pub const F_ERR: c_int = 32;
pub const F_SVB: c_int = 64;
pub const F_APP: c_int = 128;
pub const F_BADJ: c_int = 256;
pub const SEEK_SET: c_int = 0;
pub const SEEK_CUR: c_int = 1;
pub const SEEK_END: c_int = 2;
pub const _IOFBF: c_int = 0;
pub const _IOLBF: c_int = 1;
pub const _IONBF: c_int = 2;
#[allow(non_camel_case_types)]
pub type fpos_t = off_t;
+61
View File
@@ -0,0 +1,61 @@
use super::{constants, BUFSIZ, FILE, UNGET};
use core::cell::UnsafeCell;
use core::ptr;
use core::sync::atomic::AtomicBool;
pub struct GlobalFile(UnsafeCell<FILE>);
impl GlobalFile {
const fn new(file: FILE) -> Self {
GlobalFile(UnsafeCell::new(file))
}
pub fn get(&self) -> *mut FILE {
self.0.get()
}
}
// statics need to be Sync
unsafe impl Sync for GlobalFile {}
lazy_static! {
#[allow(non_upper_case_globals)]
pub static ref default_stdin: GlobalFile = GlobalFile::new(FILE {
flags: constants::F_PERM | constants::F_NOWR,
read: None,
write: None,
fd: 0,
buf: vec![0u8;(BUFSIZ + UNGET) as usize],
buf_char: -1,
unget: UNGET,
lock: AtomicBool::new(false),
});
#[allow(non_upper_case_globals)]
pub static ref default_stdout: GlobalFile = GlobalFile::new(FILE {
flags: constants::F_PERM | constants::F_NORD,
read: None,
write: None,
fd: 1,
buf: vec![0u8;(BUFSIZ + UNGET) as usize],
buf_char: b'\n' as i8,
unget: 0,
lock: AtomicBool::new(false),
});
#[allow(non_upper_case_globals)]
pub static ref default_stderr: GlobalFile = GlobalFile::new(FILE {
flags: constants::F_PERM | constants::F_NORD,
read: None,
write: None,
fd: 2,
buf: vec![0u8;(BUFSIZ + UNGET) as usize],
buf_char: -1,
unget: 0,
lock: AtomicBool::new(false),
});
}
#[no_mangle]
pub static mut stdin: *mut FILE = ptr::null_mut();
#[no_mangle]
pub static mut stdout: *mut FILE = ptr::null_mut();
#[no_mangle]
pub static mut stderr: *mut FILE = ptr::null_mut();
+154
View File
@@ -0,0 +1,154 @@
use super::constants::*;
use super::{BUFSIZ, FILE, UNGET};
use core::mem;
use core::sync::atomic::AtomicBool;
use errno;
use fcntl::*;
use platform;
use platform::types::*;
/// Parse mode flags as a string and output a mode flags integer
pub unsafe fn parse_mode_flags(mode_str: *const c_char) -> i32 {
use string::strchr;
let mut flags = if !strchr(mode_str, b'+' as i32).is_null() {
O_RDWR
} else if (*mode_str) == b'r' as i8 {
O_RDONLY
} else {
O_WRONLY
};
if !strchr(mode_str, b'x' as i32).is_null() {
flags |= O_EXCL;
}
if !strchr(mode_str, b'e' as i32).is_null() {
flags |= O_CLOEXEC;
}
if (*mode_str) != b'r' as i8 {
flags |= O_CREAT;
}
if (*mode_str) == b'w' as i8 {
flags |= O_TRUNC;
}
if (*mode_str) != b'a' as i8 {
flags |= O_APPEND;
}
flags
}
/// Open a file with the file descriptor `fd` in the mode `mode`
pub unsafe fn _fdopen(fd: c_int, mode: *const c_char) -> Option<*mut FILE> {
use string::strchr;
if *mode != b'r' as i8 && *mode != b'w' as i8 && *mode != b'a' as i8 {
platform::errno = errno::EINVAL;
return None;
}
let mut flags = 0;
if strchr(mode, b'+' as i32).is_null() {
flags |= if *mode == b'r' as i8 { F_NOWR } else { F_NORD };
}
if !strchr(mode, b'e' as i32).is_null() {
sys_fcntl(fd, F_SETFD, FD_CLOEXEC);
}
if *mode == 'a' as i8 {
let f = sys_fcntl(fd, F_GETFL, 0);
if (f & O_APPEND) == 0 {
sys_fcntl(fd, F_SETFL, f | O_APPEND);
}
flags |= F_APP;
}
let f = platform::alloc(mem::size_of::<FILE>()) as *mut FILE;
// Allocate the file
if f.is_null() {
None
} else {
(*f).flags = flags;
(*f).read = None;
(*f).write = None;
(*f).fd = fd;
(*f).buf = vec![0u8; BUFSIZ + UNGET];
(*f).buf_char = -1;
(*f).unget = UNGET;
(*f).lock = AtomicBool::new(false);
Some(f)
}
}
/// Write buffer `buf` of length `l` into `stream`
pub fn fwritex(buf: *const u8, l: size_t, stream: &mut FILE) -> size_t {
use core::ptr::copy_nonoverlapping;
use core::slice;
let buf: &'static [u8] = unsafe { slice::from_raw_parts(buf, l) };
let mut l = l;
let mut advance = 0;
if stream.write.is_none() && !stream.can_write() {
// We can't write to this stream
return 0;
}
if let Some((wbase, wpos, wend)) = stream.write {
if l > wend - wpos {
// We can't fit all of buf in the buffer
return stream.write(buf);
}
let i = if stream.buf_char >= 0 {
let mut i = l;
while i > 0 && buf[i - 1] != b'\n' {
i -= 1;
}
if i > 0 {
let n = stream.write(buf);
if n < i {
return n;
}
advance += i;
l -= i;
}
i
} else {
0
};
unsafe {
copy_nonoverlapping(
&buf[advance..] as *const _ as *const u8,
&mut stream.buf[wpos..] as *mut _ as *mut u8,
l,
);
}
stream.write = Some((wbase, wpos + l, wend));
l + i
} else {
0
}
}
/// Flush `stream` without locking it.
pub fn fflush_unlocked(stream: &mut FILE) -> c_int {
if let Some((wbase, wpos, _)) = stream.write {
if wpos > wbase {
stream.write(&[]);
/*
if stream.wpos.is_null() {
return -1;
}
*/
}
}
if let Some((rpos, rend)) = stream.read {
if rpos < rend {
stream.seek(rpos as i64 - rend as i64, SEEK_CUR);
}
}
stream.write = None;
stream.read = None;
0
}
+31
View File
@@ -0,0 +1,31 @@
use super::{constants, FILE};
use platform::types::*;
pub fn ftello(stream: &mut FILE) -> off_t {
let pos = stream.seek(
0,
if let Some((wbase, wpos, _)) = stream.write {
if (stream.flags & constants::F_APP > 0) && wpos > wbase {
constants::SEEK_END
} else {
constants::SEEK_CUR
}
} else {
constants::SEEK_CUR
},
);
if pos < 0 {
return pos;
}
let rdiff = if let Some((rpos, rend)) = stream.read {
rend - rpos
} else {
0
};
let wdiff = if let Some((wbase, wpos, _)) = stream.write {
wpos - wbase
} else {
0
};
pos - rdiff as i64 + wdiff as i64
}
+989
View File
@@ -0,0 +1,989 @@
//! stdio implementation for Redox, following http://pubs.opengroup.org/onlinepubs/7908799/xsh/stdio.h.html
use alloc::vec::Vec;
use core::fmt::Write as WriteFmt;
use core::fmt::{self, Error};
use core::sync::atomic::{AtomicBool, Ordering};
use core::{ptr, str};
use va_list::VaList as va_list;
use header::errno::{self, STR_ERROR};
use header::{fcntl, string};
use platform;
use platform::{Pal, Sys};
use platform::types::*;
use platform::{c_str, errno, Read, Write};
mod printf;
mod scanf;
mod default;
pub use default::*;
mod constants;
pub use constants::*;
mod helpers;
mod internal;
///
/// This struct gets exposed to the C API.
///
pub struct FILE {
flags: i32,
read: Option<(usize, usize)>,
write: Option<(usize, usize, usize)>,
fd: c_int,
buf: Vec<u8>,
buf_char: i8,
lock: AtomicBool,
unget: usize,
}
impl FILE {
pub fn can_read(&mut self) -> bool {
/*
if self.flags & constants::F_BADJ > 0 {
// Static and needs unget region
self.buf = unsafe { self.buf.add(self.unget) };
self.flags &= !constants::F_BADJ;
}
*/
if let Some(_) = self.read {
return true;
}
if let Some(_) = self.write {
self.write(&[]);
}
self.write = None;
if self.flags & constants::F_NORD > 0 {
self.flags |= constants::F_ERR;
return false;
}
self.read = if self.buf.len() == 0 {
Some((0, 0))
} else {
Some((self.buf.len() - 1, self.buf.len() - 1))
};
if self.flags & constants::F_EOF > 0 {
false
} else {
true
}
}
pub fn can_write(&mut self) -> bool {
/*
if self.flags & constants::F_BADJ > 0 {
// Static and needs unget region
self.buf = unsafe { self.buf.add(self.unget) };
self.flags &= !constants::F_BADJ;
}
*/
if self.flags & constants::F_NOWR > 0 {
self.flags &= constants::F_ERR;
return false;
}
// Buffer repositioning
if let Some(_) = self.write {
return true;
}
self.read = None;
self.write = if self.buf.len() == 0 {
Some((0, 0, 0))
} else {
Some((self.unget, self.unget, self.buf.len() - 1))
};
return true;
}
pub fn write(&mut self, to_write: &[u8]) -> usize {
if let Some((wbase, wpos, _)) = self.write {
let len = wpos - wbase;
let mut advance = 0;
let mut f_buf = &self.buf[wbase..wpos];
let mut f_filled = false;
let mut rem = f_buf.len() + to_write.len();
loop {
let mut count = if f_filled {
Sys::write(self.fd, &f_buf[advance..])
} else {
Sys::write(self.fd, &f_buf[advance..]) + Sys::write(self.fd, to_write)
};
if count == rem as isize {
self.write = if self.buf.len() == 0 {
Some((0, 0, 0))
} else {
Some((self.unget, self.unget, self.buf.len() - 1))
};
return to_write.len();
}
if count < 0 {
self.write = None;
self.flags |= constants::F_ERR;
return 0;
}
rem -= count as usize;
if count as usize > len {
count -= len as isize;
f_buf = to_write;
f_filled = true;
advance = 0;
}
advance += count as usize;
}
}
// self.can_write() should always be called before self.write()
// and should automatically fill self.write if it returns true.
// Thus, we should never reach this
// -- Tommoa (20/6/2018)
unreachable!()
}
pub fn read(&mut self, buf: &mut [u8]) -> usize {
let adj = if self.buf.len() > 0 { 0 } else { 1 };
let mut file_buf = &mut self.buf[self.unget..];
let count = if buf.len() <= 1 - adj {
Sys::read(self.fd, &mut file_buf)
} else {
Sys::read(self.fd, buf) + Sys::read(self.fd, &mut file_buf)
};
if count <= 0 {
self.flags |= if count == 0 {
constants::F_EOF
} else {
constants::F_ERR
};
return 0;
}
if count as usize <= buf.len() - adj {
return count as usize;
}
// Adjust pointers
if file_buf.len() == 0 {
self.read = Some((0, 0));
} else if buf.len() > 0 {
self.read = Some((self.unget + 1, self.unget + (count as usize)));
buf[buf.len() - 1] = file_buf[0];
} else {
self.read = Some((self.unget, self.unget + (count as usize)));
}
buf.len()
}
pub fn seek(&self, off: off_t, whence: c_int) -> off_t {
Sys::lseek(self.fd, off, whence)
}
pub fn lock(&mut self) -> LockGuard {
flockfile(self);
LockGuard(self)
}
}
pub struct LockGuard<'a>(&'a mut FILE);
impl<'a> Drop for LockGuard<'a> {
fn drop(&mut self) {
funlockfile(self.0);
}
}
impl<'a> fmt::Write for LockGuard<'a> {
fn write_str(&mut self, s: &str) -> fmt::Result {
if !self.0.can_write() {
return Err(Error);
}
let s = s.as_bytes();
if self.0.write(s) != s.len() {
Err(Error)
} else {
Ok(())
}
}
}
impl<'a> Write for LockGuard<'a> {
fn write_u8(&mut self, byte: u8) -> fmt::Result {
if !self.0.can_write() {
return Err(Error);
}
if self.0.write(&[byte]) != 1 {
Err(Error)
} else {
Ok(())
}
}
}
impl<'a> Read for LockGuard<'a> {
fn read_u8(&mut self) -> Result<Option<u8>, ()> {
let mut buf = [0];
match self.0.read(&mut buf) {
0 => Ok(None),
_ => Ok(Some(buf[0]))
}
}
}
impl Drop for FILE {
fn drop(&mut self) {
// Flush
if let Some(_) = self.write {
self.write(&[]);
}
}
}
/// Clears EOF and ERR indicators on a stream
#[no_mangle]
pub extern "C" fn clearerr(stream: &mut FILE) {
stream.flags &= !(F_EOF | F_ERR);
}
// #[no_mangle]
pub extern "C" fn ctermid(_s: *mut c_char) -> *mut c_char {
unimplemented!();
}
// #[no_mangle]
pub extern "C" fn cuserid(_s: *mut c_char) -> *mut c_char {
unimplemented!();
}
/// 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.
#[no_mangle]
pub extern "C" fn fclose(stream: &mut FILE) -> c_int {
flockfile(stream);
let r = helpers::fflush_unlocked(stream) | Sys::close(stream.fd);
if stream.flags & constants::F_PERM == 0 {
// Not one of stdin, stdout or stderr
unsafe {
platform::free(stream as *mut FILE as *mut c_void);
}
} else {
funlockfile(stream);
}
r
}
/// Open a file from a file descriptor
#[no_mangle]
pub extern "C" fn fdopen(fildes: c_int, mode: *const c_char) -> *mut FILE {
use core::ptr;
if let Some(f) = unsafe { helpers::_fdopen(fildes, mode) } {
f
} else {
ptr::null_mut()
}
}
/// Check for EOF
#[no_mangle]
pub extern "C" fn feof(stream: &mut FILE) -> c_int {
flockfile(stream);
let ret = stream.flags & F_EOF;
funlockfile(stream);
ret
}
/// Check for ERR
#[no_mangle]
pub extern "C" fn ferror(stream: &mut FILE) -> c_int {
flockfile(stream);
let ret = stream.flags & F_ERR;
funlockfile(stream);
ret
}
/// 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.
#[no_mangle]
pub unsafe extern "C" fn fflush(stream: &mut FILE) -> c_int {
flockfile(stream);
let ret = helpers::fflush_unlocked(stream);
funlockfile(stream);
ret
}
/// Get a single char from a stream
#[no_mangle]
pub extern "C" fn fgetc(stream: &mut FILE) -> c_int {
flockfile(stream);
let c = getc_unlocked(stream);
funlockfile(stream);
c
}
/// Get the position of the stream and store it in pos
#[no_mangle]
pub extern "C" fn fgetpos(stream: &mut FILE, pos: Option<&mut fpos_t>) -> c_int {
let off = internal::ftello(stream);
if off < 0 {
return -1;
}
if let Some(pos) = pos {
*pos = off;
0
} else {
-1
}
}
/// Get a string from the stream
#[no_mangle]
pub extern "C" fn fgets(s: *mut c_char, n: c_int, stream: &mut FILE) -> *mut c_char {
use core::slice;
flockfile(stream);
let st = unsafe { slice::from_raw_parts_mut(s as *mut u8, n as usize) };
let mut len = n;
// We can only fit one or less chars in
if n <= 1 {
funlockfile(stream);
if n <= 0 {
return ptr::null_mut();
}
unsafe {
(*s) = b'\0' as i8;
}
return s;
}
// Scope this so we can reuse stream mutably
{
// We can't read from this stream
if !stream.can_read() {
return ptr::null_mut();
}
}
// TODO: Look at this later to determine correctness and efficiency
'outer: while stream.read(&mut []) == 0 && stream.flags & F_ERR == 0 {
if let Some((rpos, rend)) = stream.read {
let mut idiff = 0usize;
for _ in (0..(len - 1) as usize).take_while(|x| rpos + x < rend) {
let pos = (n - len) as usize;
st[pos] = stream.buf[rpos + idiff];
idiff += 1;
len -= 1;
if st[pos] == b'\n' || st[pos] as i8 == stream.buf_char {
break 'outer;
}
}
stream.read = Some((rpos + idiff, rend));
if rend - rpos == 0 {
len -= stream.read(&mut st[((n - len) as usize)..]) as i32;
break;
}
if len <= 1 {
break;
}
}
// We can read, there's been no errors. We should have stream.read setbuf
// -- Tommoa (3/7/2018)
unreachable!()
}
st[(n - len) as usize] = 0;
funlockfile(stream);
s
}
/// Get the underlying file descriptor
#[no_mangle]
pub extern "C" fn fileno(stream: &mut FILE) -> c_int {
flockfile(stream);
funlockfile(stream);
stream.fd
}
/// Lock the file
/// Do not call any functions other than those with the `_unlocked` postfix while the file is
/// locked
#[no_mangle]
pub extern "C" fn flockfile(file: &mut FILE) {
while ftrylockfile(file) != 0 {}
}
/// Open the file in mode `mode`
#[no_mangle]
pub extern "C" fn fopen(filename: *const c_char, mode: *const c_char) -> *mut FILE {
use core::ptr;
let initial_mode = unsafe { *mode };
if initial_mode != b'r' as i8 && initial_mode != b'w' as i8 && initial_mode != b'a' as i8 {
unsafe { platform::errno = errno::EINVAL };
return ptr::null_mut();
}
let flags = unsafe { helpers::parse_mode_flags(mode) };
let fd = fcntl::sys_open(filename, flags, 0o666);
if fd < 0 {
return ptr::null_mut();
}
if flags & fcntl::O_CLOEXEC > 0 {
fcntl::sys_fcntl(fd, fcntl::F_SETFD, fcntl::FD_CLOEXEC);
}
if let Some(f) = unsafe { helpers::_fdopen(fd, mode) } {
f
} else {
Sys::close(fd);
ptr::null_mut()
}
}
/// Insert a character into the stream
#[no_mangle]
pub extern "C" fn fputc(c: c_int, stream: &mut FILE) -> c_int {
flockfile(stream);
let c = putc_unlocked(c, stream);
funlockfile(stream);
c
}
/// Insert a string into a stream
#[no_mangle]
pub extern "C" fn fputs(s: *const c_char, stream: &mut FILE) -> c_int {
extern "C" {
fn strlen(s: *const c_char) -> size_t;
}
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`
#[no_mangle]
pub extern "C" fn fread(ptr: *mut c_void, size: usize, nitems: usize, stream: &mut FILE) -> usize {
use core::ptr::copy_nonoverlapping;
use core::slice;
let mut dest = ptr as *mut u8;
let len = size * nitems;
let mut l = len as isize;
flockfile(stream);
if !stream.can_read() {
return 0;
}
if let Some((rpos, rend)) = stream.read {
if rend > rpos {
// We have some buffered data that can be read
let diff = rend - rpos;
let k = if diff < l as usize { diff } else { l as usize };
unsafe {
// Copy data
copy_nonoverlapping(&stream.buf[rpos..] as *const _ as *const u8, dest, k);
// Reposition pointers
dest = dest.add(k);
}
stream.read = Some((rpos + k, rend));
l -= k as isize;
}
while l > 0 {
let k = if !stream.can_read() {
0
} else {
stream.read(unsafe { slice::from_raw_parts_mut(dest, l as usize) })
};
if k == 0 {
funlockfile(stream);
return (len - l as usize) / 2;
}
l -= k as isize;
unsafe {
// Reposition
dest = dest.add(k);
}
}
funlockfile(stream);
nitems
} else {
unreachable!()
}
}
#[no_mangle]
pub extern "C" fn freopen(
filename: *const c_char,
mode: *const c_char,
stream: &mut FILE,
) -> *mut FILE {
let mut flags = unsafe { helpers::parse_mode_flags(mode) };
flockfile(stream);
helpers::fflush_unlocked(stream);
if filename.is_null() {
// Reopen stream in new mode
if flags & fcntl::O_CLOEXEC > 0 {
fcntl::sys_fcntl(stream.fd, fcntl::F_SETFD, fcntl::FD_CLOEXEC);
}
flags &= !(fcntl::O_CREAT | fcntl::O_EXCL | fcntl::O_CLOEXEC);
if fcntl::sys_fcntl(stream.fd, fcntl::F_SETFL, flags) < 0 {
funlockfile(stream);
fclose(stream);
return ptr::null_mut();
}
} else {
let new = fopen(filename, mode);
if new.is_null() {
funlockfile(stream);
fclose(stream);
return ptr::null_mut();
}
let new = unsafe { &mut *new }; // Should be safe, new is not null
if new.fd == stream.fd {
new.fd = -1;
} else if Sys::dup2(new.fd, stream.fd) < 0
|| fcntl::sys_fcntl(stream.fd, fcntl::F_SETFL, flags & fcntl::O_CLOEXEC) < 0
{
fclose(new);
funlockfile(stream);
fclose(stream);
return ptr::null_mut();
}
stream.flags = (stream.flags & constants::F_PERM) | new.flags;
fclose(new);
}
funlockfile(stream);
stream
}
/// Seek to an offset `offset` from `whence`
#[no_mangle]
pub extern "C" fn fseek(stream: &mut FILE, offset: c_long, whence: c_int) -> c_int {
if fseeko(stream, offset as off_t, whence) != -1 {
return 0;
}
-1
}
/// Seek to an offset `offset` from `whence`
#[no_mangle]
pub extern "C" fn fseeko(stream: &mut FILE, offset: off_t, whence: c_int) -> c_int {
let mut off = offset;
flockfile(stream);
// Adjust for what is currently in the buffer
let rdiff = if let Some((rpos, rend)) = stream.read {
rend - rpos
} else {
0
};
if whence == SEEK_CUR {
off -= (rdiff) as i64;
}
if let Some(_) = stream.write {
stream.write(&[]);
}
stream.write = None;
if stream.seek(off, whence) < 0 {
return -1;
}
stream.read = None;
stream.flags &= !F_EOF;
funlockfile(stream);
0
}
/// Seek to a position `pos` in the file from the beginning of the file
#[no_mangle]
pub unsafe extern "C" fn fsetpos(stream: &mut FILE, pos: Option<&fpos_t>) -> c_int {
fseek(
stream,
*pos.expect("You must specify a valid position"),
SEEK_SET,
)
}
/// Get the current position of the cursor in the file
#[no_mangle]
pub extern "C" fn ftell(stream: &mut FILE) -> c_long {
ftello(stream) as c_long
}
/// Get the current position of the cursor in the file
#[no_mangle]
pub extern "C" fn ftello(stream: &mut FILE) -> off_t {
flockfile(stream);
let pos = internal::ftello(stream);
funlockfile(stream);
pos
}
/// Try to lock the file. Returns 0 for success, 1 for failure
#[no_mangle]
pub extern "C" fn ftrylockfile(file: &mut FILE) -> c_int {
file.lock.compare_and_swap(false, true, Ordering::Acquire) as c_int
}
/// Unlock the file
#[no_mangle]
pub extern "C" fn funlockfile(file: &mut FILE) {
file.lock.store(false, Ordering::Release);
}
/// Write `nitems` of size `size` from `ptr` to `stream`
#[no_mangle]
pub extern "C" fn fwrite(
ptr: *const c_void,
size: usize,
nitems: usize,
stream: &mut FILE,
) -> usize {
let l = size * nitems;
let nitems = if size == 0 { 0 } else { nitems };
flockfile(stream);
let k = helpers::fwritex(ptr as *const u8, l, stream);
funlockfile(stream);
if k == l {
nitems
} else {
k / size
}
}
/// Get a single char from a stream
#[no_mangle]
pub extern "C" fn getc(stream: &mut FILE) -> c_int {
flockfile(stream);
let c = getc_unlocked(stream);
funlockfile(stream);
c
}
/// Get a single char from `stdin`
#[no_mangle]
pub extern "C" fn getchar() -> c_int {
fgetc(unsafe { &mut *stdin })
}
/// Get a char from a stream without locking the stream
#[no_mangle]
pub extern "C" fn getc_unlocked(stream: &mut FILE) -> c_int {
if !stream.can_read() {
return -1;
}
if let Some((rpos, rend)) = stream.read {
if rpos < rend {
let ret = stream.buf[rpos] as c_int;
stream.read = Some((rpos + 1, rend));
ret
} else {
let mut c = [0u8; 1];
if stream.read(&mut c) == 1 {
c[0] as c_int
} else {
-1
}
}
} else {
// We made a prior call to can_read() and are checking it, therefore we
// should never be in a case where stream.read is None
// -- Tommoa (20/6/2018)
unreachable!()
}
}
/// Get a char from `stdin` without locking `stdin`
#[no_mangle]
pub extern "C" fn getchar_unlocked() -> c_int {
getc_unlocked(unsafe { &mut *stdin })
}
/// Get a string from `stdin`
#[no_mangle]
pub extern "C" fn gets(s: *mut c_char) -> *mut c_char {
use core::i32;
fgets(s, i32::MAX, unsafe { &mut *stdin })
}
/// Get an integer from `stream`
#[no_mangle]
pub extern "C" fn getw(stream: &mut FILE) -> c_int {
use core::mem;
let mut ret: c_int = 0;
if fread(
&mut ret as *mut c_int as *mut c_void,
mem::size_of_val(&ret),
1,
stream,
) > 0
{
ret
} else {
-1
}
}
// #[no_mangle]
pub extern "C" fn pclose(_stream: &mut FILE) -> c_int {
unimplemented!();
}
#[no_mangle]
pub unsafe extern "C" fn perror(s: *const c_char) {
let s_str = str::from_utf8_unchecked(c_str(s));
let mut w = platform::FileWriter(2);
if errno >= 0 && errno < STR_ERROR.len() as c_int {
w.write_fmt(format_args!("{}: {}\n", s_str, STR_ERROR[errno as usize]))
.unwrap();
} else {
w.write_fmt(format_args!("{}: Unknown error {}\n", s_str, errno))
.unwrap();
}
}
// #[no_mangle]
pub extern "C" fn popen(_command: *const c_char, _mode: *const c_char) -> *mut FILE {
unimplemented!();
}
/// Put a character `c` into `stream`
#[no_mangle]
pub extern "C" fn putc(c: c_int, stream: &mut FILE) -> c_int {
flockfile(stream);
let ret = putc_unlocked(c, stream);
funlockfile(stream);
ret
}
/// Put a character `c` into `stdout`
#[no_mangle]
pub extern "C" fn putchar(c: c_int) -> c_int {
fputc(c, unsafe { &mut *stdout })
}
/// Put a character `c` into `stream` without locking `stream`
#[no_mangle]
pub extern "C" fn putc_unlocked(c: c_int, stream: &mut FILE) -> c_int {
if stream.can_write() {
if let Some((wbase, wpos, wend)) = stream.write {
if c as i8 != stream.buf_char {
stream.buf[wpos] = c as u8;
stream.write = Some((wbase, wpos + 1, wend));
c
} else if stream.write(&[c as u8]) == 1 {
c
} else {
-1
}
} else {
-1
}
} else {
-1
}
}
/// Put a character `c` into `stdout` without locking `stdout`
#[no_mangle]
pub extern "C" fn putchar_unlocked(c: c_int) -> c_int {
putc_unlocked(c, unsafe { &mut *stdout })
}
/// Put a string `s` into `stdout`
#[no_mangle]
pub extern "C" fn puts(s: *const c_char) -> c_int {
let ret = (fputs(s, unsafe { &mut *stdout }) > 0) || (putchar_unlocked(b'\n' as c_int) > 0);
if ret {
0
} else {
-1
}
}
/// Put an integer `w` into `stream`
#[no_mangle]
pub extern "C" fn putw(w: c_int, stream: &mut FILE) -> c_int {
use core::mem;
fwrite(&w as *const i32 as _, mem::size_of_val(&w), 1, stream) as i32 - 1
}
/// Delete file or directory `path`
#[no_mangle]
pub extern "C" fn remove(path: *const c_char) -> c_int {
let r = Sys::unlink(path);
if r == -errno::EISDIR {
Sys::rmdir(path)
} else {
r
}
}
#[no_mangle]
pub extern "C" fn rename(oldpath: *const c_char, newpath: *const c_char) -> c_int {
Sys::rename(oldpath, newpath)
}
/// Rewind `stream` back to the beginning of it
#[no_mangle]
pub extern "C" fn rewind(stream: &mut FILE) {
fseeko(stream, 0, SEEK_SET);
flockfile(stream);
stream.flags &= !F_ERR;
funlockfile(stream);
}
/// Reset `stream` to use buffer `buf`. Buffer must be `BUFSIZ` in length
#[no_mangle]
pub extern "C" fn setbuf(stream: &mut FILE, buf: *mut c_char) {
setvbuf(
stream,
buf,
if buf.is_null() { _IONBF } else { _IOFBF },
BUFSIZ as usize,
);
}
/// Reset `stream` to use buffer `buf` of size `size`
/// If this isn't the meaning of unsafe, idk what is
#[no_mangle]
pub extern "C" fn setvbuf(stream: &mut FILE, buf: *mut c_char, mode: c_int, size: usize) -> c_int {
// Set a buffer of size `size` if no buffer is given
let buf = if buf.is_null() {
if mode != _IONBF {
vec![0u8; 1]
} else {
stream.unget = 0;
if let Some(_) = stream.write {
stream.write = Some((0, 0, 0));
} else if let Some(_) = stream.read {
stream.read = Some((0, 0));
}
Vec::new()
}
} else {
// We trust the user on this one
// -- Tommoa (20/6/2018)
unsafe { Vec::from_raw_parts(buf as *mut u8, size, size) }
};
stream.buf_char = -1;
if mode == _IOLBF {
stream.buf_char = b'\n' as i8;
}
stream.flags |= F_SVB;
stream.buf = buf;
0
}
// #[no_mangle]
pub extern "C" fn tempnam(_dir: *const c_char, _pfx: *const c_char) -> *mut c_char {
unimplemented!();
}
#[no_mangle]
pub extern "C" fn tmpfile() -> *mut FILE {
extern "C" {
fn mkstemp(name: *mut c_char) -> c_int;
}
let mut file_name = *b"/tmp/tmpfileXXXXXX";
let file_name = file_name.as_mut_ptr() as *mut c_char;
let fd = unsafe { mkstemp(file_name) };
if fd < 0 {
return ptr::null_mut();
}
let fp = fdopen(fd, b"w+".as_ptr() as *const i8);
Sys::unlink(file_name);
if fp == ptr::null_mut() {
Sys::close(fd);
}
fp
}
// #[no_mangle]
pub extern "C" fn tmpnam(_s: *mut c_char) -> *mut c_char {
unimplemented!();
}
/// Push character `c` back onto `stream` so it'll be read next
#[no_mangle]
pub extern "C" fn ungetc(c: c_int, stream: &mut FILE) -> c_int {
if c < 0 {
c
} else {
flockfile(stream);
if stream.read.is_none() {
stream.can_read();
}
if let Some((rpos, rend)) = stream.read {
if rpos == 0 {
funlockfile(stream);
return -1;
}
stream.read = Some((rpos - 1, rend));
stream.buf[rpos - 1] = c as u8;
stream.flags &= !F_EOF;
funlockfile(stream);
c
} else {
funlockfile(stream);
-1
}
}
}
#[no_mangle]
pub unsafe extern "C" fn vfprintf(file: &mut FILE, format: *const c_char, ap: va_list) -> c_int {
printf::printf(file.lock(), format, ap)
}
#[no_mangle]
pub unsafe extern "C" fn vprintf(format: *const c_char, ap: va_list) -> c_int {
vfprintf(&mut *stdout, format, ap)
}
#[no_mangle]
pub unsafe extern "C" fn vsnprintf(
s: *mut c_char,
n: usize,
format: *const c_char,
ap: va_list,
) -> c_int {
printf::printf(
&mut platform::StringWriter(s as *mut u8, n as usize),
format,
ap,
)
}
#[no_mangle]
pub unsafe extern "C" fn vsprintf(s: *mut c_char, format: *const c_char, ap: va_list) -> c_int {
printf::printf(&mut platform::UnsafeStringWriter(s as *mut u8), format, ap)
}
#[no_mangle]
pub unsafe extern "C" fn vfscanf(file: &mut FILE, format: *const c_char, ap: va_list) -> c_int {
scanf::scanf(file.lock(), format, ap)
}
#[no_mangle]
pub unsafe extern "C" fn vscanf(format: *const c_char, ap: va_list) -> c_int {
vfscanf(&mut *stdin, format, ap)
}
#[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,
)
}
+115
View File
@@ -0,0 +1,115 @@
use core::fmt::Write as CoreWrite;
use core::{slice, str};
use platform::types::*;
use platform::{self, Write};
use vl::VaList;
pub unsafe fn printf<W: Write>(w: W, format: *const c_char, mut ap: VaList) -> c_int {
let mut w = platform::CountingWriter::new(w);
let format = slice::from_raw_parts(format as *const u8, usize::max_value());
let mut found_percent = false;
for &b in format.iter() {
// check for NUL
if b == 0 {
break;
}
if found_percent {
if match b as char {
'%' => {
found_percent = false;
w.write_char('%')
}
'c' => {
let a = ap.get::<u32>();
found_percent = false;
w.write_u8(a as u8)
}
'd' | 'i' => {
let a = ap.get::<c_int>();
found_percent = false;
w.write_fmt(format_args!("{}", a))
}
'f' | 'F' => {
let a = ap.get::<f64>();
found_percent = false;
w.write_fmt(format_args!("{}", a))
}
'n' => {
let _a = ap.get::<c_int>();
found_percent = false;
Ok(())
}
'p' => {
let a = ap.get::<usize>();
found_percent = false;
w.write_fmt(format_args!("0x{:x}", a))
}
's' => {
let a = ap.get::<*const c_char>();
found_percent = false;
w.write_str(str::from_utf8_unchecked(platform::c_str(a)))
}
'u' => {
let a = ap.get::<c_uint>();
found_percent = false;
w.write_fmt(format_args!("{}", a))
}
'x' => {
let a = ap.get::<c_uint>();
found_percent = false;
w.write_fmt(format_args!("{:x}", a))
}
'X' => {
let a = ap.get::<c_uint>();
found_percent = false;
w.write_fmt(format_args!("{:X}", a))
}
'o' => {
let a = ap.get::<c_uint>();
found_percent = false;
w.write_fmt(format_args!("{:o}", a))
}
'-' => Ok(()),
'+' => Ok(()),
' ' => Ok(()),
'#' => Ok(()),
'0'...'9' => Ok(()),
_ => Ok(()),
}.is_err()
{
return -1;
}
} else if b == b'%' {
found_percent = true;
} else {
if w.write_u8(b).is_err() {
return -1;
}
}
}
w.written as c_int
}
+428
View File
@@ -0,0 +1,428 @@
use alloc::String;
use alloc::Vec;
use platform::types::*;
use platform::Read;
use vl::VaList;
#[derive(PartialEq, Eq)]
enum IntKind {
Byte,
Short,
Int,
Long,
LongLong,
IntMax,
PtrDiff,
Size,
}
/// Helper function for progressing a C string
unsafe fn next_byte(string: &mut *const c_char) -> Result<u8, c_int> {
let c = **string as u8;
*string = string.offset(1);
if c == 0 {
Err(-1)
} else {
Ok(c)
}
}
unsafe fn inner_scanf<R: Read>(
mut r: R,
mut format: *const c_char,
mut ap: VaList,
) -> Result<c_int, c_int> {
let mut matched = 0;
let mut byte = 0;
let mut skip_read = false;
let mut count = 0;
macro_rules! read {
() => {{
match r.read_u8() {
Ok(Some(b)) => {
byte = b;
count += 1;
true
},
Ok(None) => false,
Err(()) => return Err(-1)
}
}};
}
macro_rules! maybe_read {
() => {
maybe_read!(inner false);
};
(noreset) => {
maybe_read!(inner);
};
(inner $($placeholder:expr)*) => {
if !skip_read {
if !read!() {
return Ok(matched);
}
}
$(else {
// Hacky way of having this optional
skip_read = $placeholder;
})*
}
}
while *format != 0 {
let mut c = *format as u8;
format = format.offset(1);
if c == b' ' {
maybe_read!(noreset);
while (byte as char).is_whitespace() {
if !read!() {
return Ok(matched);
}
}
skip_read = true;
} else if c != b'%' {
maybe_read!();
if c != byte {
return Ok(matched);
}
} else {
c = next_byte(&mut format)?;
let mut ignore = false;
if c == b'*' {
ignore = true;
c = next_byte(&mut format)?;
}
let mut width = String::new();
while c >= b'0' && c <= b'9' {
width.push(c as char);
c = next_byte(&mut format)?;
}
let mut width = if width.is_empty() {
None
} else {
match width.parse::<usize>() {
Ok(n) => Some(n),
Err(_) => return Err(-1),
}
};
let mut kind = IntKind::Int;
loop {
kind = match c {
b'h' => if kind == IntKind::Short {
IntKind::Byte
} else {
IntKind::Short
},
b'j' => IntKind::IntMax,
b'l' => IntKind::Long,
b'q' | b'L' => IntKind::LongLong,
b't' => IntKind::PtrDiff,
b'z' => IntKind::Size,
_ => break,
};
c = next_byte(&mut format)?;
}
if c != b'n' {
maybe_read!(noreset);
}
match c {
b'%' => {
while (byte as char).is_whitespace() {
if !read!() {
return Ok(matched);
}
}
if byte != b'%' {
return Err(matched);
} else if !read!() {
return Ok(matched);
}
}
b'd' | b'i' | b'o' | b'u' | b'x' | b'X' | b'f' | b'e' | b'g' | b'E' | b'a'
| b'p' => {
while (byte as char).is_whitespace() {
if !read!() {
return Ok(matched);
}
}
let pointer = c == b'p';
// Pointers aren't automatic, but we do want to parse "0x"
let auto = c == b'i' || pointer;
let float = c == b'f' || c == b'e' || c == b'g' || c == b'E' || c == b'a';
let mut radix = match c {
b'o' => 8,
b'x' | b'X' | b'p' => 16,
_ => 10,
};
let mut n = String::new();
let mut dot = false;
while width.map(|w| w > 0).unwrap_or(true)
&& ((byte >= b'0' && byte <= b'7')
|| (radix >= 10 && (byte >= b'8' && byte <= b'9'))
|| (float && !dot && byte == b'.')
|| (radix == 16
&& ((byte >= b'a' && byte <= b'f')
|| (byte >= b'A' && byte <= b'F'))))
{
if auto
&& n.is_empty()
&& byte == b'0'
&& width.map(|w| w > 0).unwrap_or(true)
{
if !pointer {
radix = 8;
}
width = width.map(|w| w - 1);
if !read!() {
break;
}
if width.map(|w| w > 0).unwrap_or(true)
&& (byte == b'x' || byte == b'X')
{
radix = 16;
width = width.map(|w| w - 1);
if width.map(|w| w > 0).unwrap_or(true) {
if !read!() {
break;
}
}
}
continue;
}
if byte == b'.' {
// Don't allow another dot
dot = true;
}
n.push(byte as char);
width = width.map(|w| w - 1);
if width.map(|w| w > 0).unwrap_or(true) {
if !read!() {
break;
}
}
}
macro_rules! parse_type {
(noformat $type:ident) => {{
let n = if n.is_empty() {
0 as $type
} else {
n.parse::<$type>().map_err(|_| 0)?
};
if !ignore {
*ap.get::<*mut $type>() = n;
matched += 1;
}
}};
(c_double) => {
parse_type!(noformat c_double);
};
(c_float) => {
parse_type!(noformat c_float);
};
($type:ident) => {
parse_type!($type, $type);
};
($type:ident, $final:ty) => {{
let n = if n.is_empty() {
0 as $type
} else {
$type::from_str_radix(&n, radix).map_err(|_| 0)?
};
if !ignore {
*ap.get::<*mut $final>() = n as $final;
matched += 1;
}
}};
}
if float {
if kind == IntKind::Long || kind == IntKind::LongLong {
parse_type!(c_double);
} else {
parse_type!(c_float);
}
} else if c == b'p' {
parse_type!(size_t, *mut c_void);
} else {
let unsigned = c == b'o' || c == b'u' || c == b'x' || c == b'X';
match kind {
IntKind::Byte => if unsigned {
parse_type!(c_uchar);
} else {
parse_type!(c_char);
},
IntKind::Short => if unsigned {
parse_type!(c_ushort)
} else {
parse_type!(c_short)
},
IntKind::Int => if unsigned {
parse_type!(c_uint)
} else {
parse_type!(c_int)
},
IntKind::Long => if unsigned {
parse_type!(c_ulong)
} else {
parse_type!(c_long)
},
IntKind::LongLong => if unsigned {
parse_type!(c_ulonglong)
} else {
parse_type!(c_longlong)
},
IntKind::IntMax => if unsigned {
parse_type!(uintmax_t)
} else {
parse_type!(intmax_t)
},
IntKind::PtrDiff => parse_type!(ptrdiff_t),
IntKind::Size => if unsigned {
parse_type!(size_t)
} else {
parse_type!(ssize_t)
},
}
}
}
b's' => {
while (byte as char).is_whitespace() {
if !read!() {
return Ok(matched);
}
}
let mut ptr: Option<*mut c_char> = if ignore { None } else { Some(ap.get()) };
while width.map(|w| w > 0).unwrap_or(true) && !(byte as char).is_whitespace() {
if let Some(ref mut ptr) = ptr {
**ptr = byte as c_char;
*ptr = ptr.offset(1);
}
width = width.map(|w| w - 1);
if width.map(|w| w > 0).unwrap_or(true) {
if !read!() {
break;
}
}
}
if let Some(ptr) = ptr {
*ptr = 0;
matched += 1;
}
}
b'c' => {
let mut ptr: Option<*mut c_char> = if ignore { None } else { Some(ap.get()) };
for i in 0..width.unwrap_or(1) {
if let Some(ptr) = ptr {
*ptr.offset(i as isize) = byte as c_char;
}
width = width.map(|w| w - 1);
if width.map(|w| w > 0).unwrap_or(true) {
if !read!() {
break;
}
}
}
if ptr.is_some() {
matched += 1;
}
}
b'[' => {
c = next_byte(&mut format)?;
let mut matches = Vec::new();
let mut invert = false;
if c == b'^' {
c = next_byte(&mut format)?;
invert = true;
}
let mut prev;
loop {
matches.push(c);
prev = c;
c = next_byte(&mut format)?;
if c == b'-' {
if prev == b']' {
continue;
}
c = next_byte(&mut format)?;
if c == b']' {
matches.push(b'-');
break;
}
prev += 1;
while prev < c {
matches.push(prev);
prev += 1;
}
} else if c == b']' {
break;
}
}
let mut ptr: Option<*mut c_char> = if ignore { None } else { Some(ap.get()) };
while width.map(|w| w > 0).unwrap_or(true) && !invert == matches.contains(&byte)
{
if let Some(ref mut ptr) = ptr {
**ptr = byte as c_char;
*ptr = ptr.offset(1);
}
width = width.map(|w| w - 1);
if width.map(|w| w > 0).unwrap_or(true) {
if !read!() {
break;
}
}
}
if let Some(ptr) = ptr {
*ptr = 0;
matched += 1;
}
}
b'n' => {
if !ignore {
*ap.get::<*mut c_int>() = count as c_int;
}
}
_ => return Err(-1),
}
if width != Some(0) && c != b'n' {
// It didn't hit the width, so an extra character was read and matched.
// But this character did not match so let's reuse it.
skip_read = true;
}
}
}
Ok(matched)
}
pub unsafe fn scanf<R: Read>(r: R, format: *const c_char, ap: VaList) -> c_int {
match inner_scanf(r, format, ap) {
Ok(n) => n,
Err(n) => n,
}
}