Create example userspace scheme. Remove kernel duplication of syscalls, use syscall crate instead

This commit is contained in:
Jeremy Soller 2016-09-20 16:23:28 -06:00
parent 941fc0b494
commit f60661820d
25 changed files with 374 additions and 414 deletions

View file

@ -10,6 +10,7 @@ crate-type = ["staticlib"]
[dependencies] [dependencies]
bitflags = "*" bitflags = "*"
spin = "*" spin = "*"
syscall = { path = "syscall/" }
[dependencies.goblin] [dependencies.goblin]
git = "https://github.com/m4b/goblin.git" git = "https://github.com/m4b/goblin.git"

View file

@ -28,6 +28,7 @@ clean:
cargo clean --manifest-path ion/Cargo.toml cargo clean --manifest-path ion/Cargo.toml
cargo clean --manifest-path drivers/ps2d/Cargo.toml cargo clean --manifest-path drivers/ps2d/Cargo.toml
cargo clean --manifest-path drivers/pcid/Cargo.toml cargo clean --manifest-path drivers/pcid/Cargo.toml
cargo clean --manifest-path schemes/example/Cargo.toml
rm -rf build rm -rf build
FORCE: FORCE:
@ -138,4 +139,8 @@ $(BUILD)/ps2d: drivers/ps2d/Cargo.toml drivers/ps2d/src/** $(BUILD)/libstd.rlib
$(CARGO) rustc --manifest-path $< $(CARGOFLAGS) -o $@ $(CARGO) rustc --manifest-path $< $(CARGOFLAGS) -o $@
strip $@ strip $@
$(BUILD)/initfs.rs: $(BUILD)/init $(BUILD)/ion $(BUILD)/pcid $(BUILD)/ps2d $(BUILD)/example: schemes/example/Cargo.toml schemes/example/src/** $(BUILD)/libstd.rlib
$(CARGO) rustc --manifest-path $< $(CARGOFLAGS) -o $@
strip $@
$(BUILD)/initfs.rs: $(BUILD)/init $(BUILD)/ion $(BUILD)/pcid $(BUILD)/ps2d $(BUILD)/example

View file

@ -2,10 +2,8 @@
extern crate syscall; extern crate syscall;
use std::fs::File;
use std::io::{Read, Write};
use std::thread; use std::thread;
use syscall::{iopl, Packet}; use syscall::iopl;
use pci::{Pci, PciBar, PciClass}; use pci::{Pci, PciBar, PciClass};
@ -77,20 +75,5 @@ fn main() {
unsafe { iopl(3).unwrap() }; unsafe { iopl(3).unwrap() };
enumerate_pci(); enumerate_pci();
let mut scheme = File::create(":pci").expect("pcid: failed to create pci scheme");
loop {
let mut packet = Packet::default();
scheme.read(&mut packet).expect("pcid: failed to read events from pci scheme");
println!("{:?}", packet);
if packet.a == 5 {
println!("{}", unsafe { ::std::str::from_utf8_unchecked(::std::slice::from_raw_parts(packet.b as *const u8, packet.c)) });
}
packet.a = 0;
scheme.write(&packet).expect("pcid: failed to write responses to pci scheme");
}
}); });
} }

View file

@ -1,9 +1,5 @@
use io::{Io, Pio, ReadOnly, WriteOnly}; use io::{Io, Pio, ReadOnly, WriteOnly};
pub unsafe fn init() {
Ps2::new().init();
}
bitflags! { bitflags! {
flags StatusFlags: u8 { flags StatusFlags: u8 {
const OUTPUT_FULL = 1, const OUTPUT_FULL = 1,

View file

@ -5,7 +5,7 @@ use core::sync::atomic::Ordering;
use spin::RwLock; use spin::RwLock;
use arch; use arch;
use syscall::{Result, Error}; use syscall::error::{Result, Error, EAGAIN};
use super::context::Context; use super::context::Context;
/// Context list type /// Context list type
@ -48,7 +48,7 @@ impl ContextList {
} }
if self.next_id >= super::CONTEXT_MAX_CONTEXTS { if self.next_id >= super::CONTEXT_MAX_CONTEXTS {
return Err(Error::TryAgain); return Err(Error::new(EAGAIN));
} }
let id = self.next_id; let id = self.next_id;

View file

@ -3,8 +3,8 @@ use core::str;
use spin::{Mutex, Once}; use spin::{Mutex, Once};
use context; use context;
use syscall::Result; use syscall::error::*;
use super::Scheme; use syscall::scheme::Scheme;
/// Input /// Input
static INPUT: Once<Mutex<VecDeque<u8>>> = Once::new(); static INPUT: Once<Mutex<VecDeque<u8>>> = Once::new();
@ -62,12 +62,12 @@ impl Scheme for DebugScheme {
Ok(buffer.len()) Ok(buffer.len())
} }
fn fsync(&self, _file: usize) -> Result<()> { fn fsync(&self, _file: usize) -> Result<usize> {
Ok(()) Ok(0)
} }
/// Close the file `number` /// Close the file `number`
fn close(&self, _file: usize) -> Result<()> { fn close(&self, _file: usize) -> Result<usize> {
Ok(()) Ok(0)
} }
} }

View file

@ -2,8 +2,8 @@ use collections::BTreeMap;
use core::sync::atomic::{AtomicUsize, Ordering}; use core::sync::atomic::{AtomicUsize, Ordering};
use spin::RwLock; use spin::RwLock;
use syscall::{Error, Result}; use syscall::error::*;
use super::Scheme; use syscall::scheme::Scheme;
struct Handle { struct Handle {
data: &'static [u8], data: &'static [u8],
@ -35,7 +35,7 @@ impl EnvScheme {
impl Scheme for EnvScheme { impl Scheme for EnvScheme {
fn open(&self, path: &[u8], _flags: usize) -> Result<usize> { fn open(&self, path: &[u8], _flags: usize) -> Result<usize> {
let data = self.files.get(path).ok_or(Error::NoEntry)?; let data = self.files.get(path).ok_or(Error::new(ENOENT))?;
let id = self.next_id.fetch_add(1, Ordering::SeqCst); let id = self.next_id.fetch_add(1, Ordering::SeqCst);
self.handles.write().insert(id, Handle { self.handles.write().insert(id, Handle {
@ -49,7 +49,7 @@ impl Scheme for EnvScheme {
fn dup(&self, file: usize) -> Result<usize> { fn dup(&self, file: usize) -> Result<usize> {
let (data, seek) = { let (data, seek) = {
let handles = self.handles.read(); let handles = self.handles.read();
let handle = handles.get(&file).ok_or(Error::BadFile)?; let handle = handles.get(&file).ok_or(Error::new(EBADF))?;
(handle.data, handle.seek) (handle.data, handle.seek)
}; };
@ -64,7 +64,7 @@ impl Scheme for EnvScheme {
fn read(&self, file: usize, buffer: &mut [u8]) -> Result<usize> { fn read(&self, file: usize, buffer: &mut [u8]) -> Result<usize> {
let mut handles = self.handles.write(); let mut handles = self.handles.write();
let mut handle = handles.get_mut(&file).ok_or(Error::BadFile)?; let mut handle = handles.get_mut(&file).ok_or(Error::new(EBADF))?;
let mut i = 0; let mut i = 0;
while i < buffer.len() && handle.seek < handle.data.len() { while i < buffer.len() && handle.seek < handle.data.len() {
@ -76,15 +76,11 @@ impl Scheme for EnvScheme {
Ok(i) Ok(i)
} }
fn write(&self, _file: usize, _buffer: &[u8]) -> Result<usize> { fn fsync(&self, _file: usize) -> Result<usize> {
Err(Error::NotPermitted) Ok(0)
} }
fn fsync(&self, _file: usize) -> Result<()> { fn close(&self, file: usize) -> Result<usize> {
Ok(()) self.handles.write().remove(&file).ok_or(Error::new(EBADF)).and(Ok(0))
}
fn close(&self, file: usize) -> Result<()> {
self.handles.write().remove(&file).ok_or(Error::BadFile).and(Ok(()))
} }
} }

View file

@ -2,8 +2,8 @@ use collections::BTreeMap;
use core::sync::atomic::{AtomicUsize, Ordering}; use core::sync::atomic::{AtomicUsize, Ordering};
use spin::RwLock; use spin::RwLock;
use syscall::{Error, Result}; use syscall::error::*;
use super::Scheme; use syscall::scheme::Scheme;
struct Handle { struct Handle {
data: &'static [u8], data: &'static [u8],
@ -24,7 +24,8 @@ impl InitFsScheme {
files.insert(b"bin/ion", include_bytes!("../../build/userspace/ion")); files.insert(b"bin/ion", include_bytes!("../../build/userspace/ion"));
files.insert(b"bin/pcid", include_bytes!("../../build/userspace/pcid")); files.insert(b"bin/pcid", include_bytes!("../../build/userspace/pcid"));
files.insert(b"bin/ps2d", include_bytes!("../../build/userspace/ps2d")); files.insert(b"bin/ps2d", include_bytes!("../../build/userspace/ps2d"));
files.insert(b"etc/init.rc", b"initfs:bin/pcid\ninitfs:bin/ps2d\ninitfs:bin/ion"); files.insert(b"bin/example", include_bytes!("../../build/userspace/example"));
files.insert(b"etc/init.rc", b"initfs:bin/pcid\ninitfs:bin/ps2d\ninitfs:bin/example\ninitfs:bin/ion");
InitFsScheme { InitFsScheme {
next_id: AtomicUsize::new(0), next_id: AtomicUsize::new(0),
@ -36,7 +37,7 @@ impl InitFsScheme {
impl Scheme for InitFsScheme { impl Scheme for InitFsScheme {
fn open(&self, path: &[u8], _flags: usize) -> Result<usize> { fn open(&self, path: &[u8], _flags: usize) -> Result<usize> {
let data = self.files.get(path).ok_or(Error::NoEntry)?; let data = self.files.get(path).ok_or(Error::new(ENOENT))?;
let id = self.next_id.fetch_add(1, Ordering::SeqCst); let id = self.next_id.fetch_add(1, Ordering::SeqCst);
self.handles.write().insert(id, Handle { self.handles.write().insert(id, Handle {
@ -50,7 +51,7 @@ impl Scheme for InitFsScheme {
fn dup(&self, file: usize) -> Result<usize> { fn dup(&self, file: usize) -> Result<usize> {
let (data, seek) = { let (data, seek) = {
let handles = self.handles.read(); let handles = self.handles.read();
let handle = handles.get(&file).ok_or(Error::BadFile)?; let handle = handles.get(&file).ok_or(Error::new(EBADF))?;
(handle.data, handle.seek) (handle.data, handle.seek)
}; };
@ -65,7 +66,7 @@ impl Scheme for InitFsScheme {
fn read(&self, file: usize, buffer: &mut [u8]) -> Result<usize> { fn read(&self, file: usize, buffer: &mut [u8]) -> Result<usize> {
let mut handles = self.handles.write(); let mut handles = self.handles.write();
let mut handle = handles.get_mut(&file).ok_or(Error::BadFile)?; let mut handle = handles.get_mut(&file).ok_or(Error::new(EBADF))?;
let mut i = 0; let mut i = 0;
while i < buffer.len() && handle.seek < handle.data.len() { while i < buffer.len() && handle.seek < handle.data.len() {
@ -77,15 +78,11 @@ impl Scheme for InitFsScheme {
Ok(i) Ok(i)
} }
fn write(&self, _file: usize, _buffer: &[u8]) -> Result<usize> { fn fsync(&self, _file: usize) -> Result<usize> {
Err(Error::NotPermitted) Ok(0)
} }
fn fsync(&self, _file: usize) -> Result<()> { fn close(&self, file: usize) -> Result<usize> {
Ok(()) self.handles.write().remove(&file).ok_or(Error::new(EBADF)).and(Ok(0))
}
fn close(&self, file: usize) -> Result<()> {
self.handles.write().remove(&file).ok_or(Error::BadFile).and(Ok(()))
} }
} }

View file

@ -1,21 +1,21 @@
use core::{mem, str}; use core::{mem, str};
use arch::interrupt::irq::{ACKS, COUNTS, acknowledge}; use arch::interrupt::irq::{ACKS, COUNTS, acknowledge};
use syscall::{Error, Result}; use syscall::error::*;
use super::Scheme; use syscall::scheme::Scheme;
pub struct IrqScheme; pub struct IrqScheme;
impl Scheme for IrqScheme { impl Scheme for IrqScheme {
fn open(&self, path: &[u8], _flags: usize) -> Result<usize> { fn open(&self, path: &[u8], _flags: usize) -> Result<usize> {
let path_str = str::from_utf8(path).or(Err(Error::NoEntry))?; let path_str = str::from_utf8(path).or(Err(Error::new(ENOENT)))?;
let id = path_str.parse::<usize>().or(Err(Error::NoEntry))?; let id = path_str.parse::<usize>().or(Err(Error::new(ENOENT)))?;
if id < COUNTS.lock().len() { if id < COUNTS.lock().len() {
Ok(id) Ok(id)
} else { } else {
Err(Error::NoEntry) Err(Error::new(ENOENT))
} }
} }
@ -37,7 +37,7 @@ impl Scheme for IrqScheme {
Ok(0) Ok(0)
} }
} else { } else {
Err(Error::InvalidValue) Err(Error::new(EINVAL))
} }
} }
@ -54,15 +54,15 @@ impl Scheme for IrqScheme {
Ok(0) Ok(0)
} }
} else { } else {
Err(Error::InvalidValue) Err(Error::new(EINVAL))
} }
} }
fn fsync(&self, _file: usize) -> Result<()> { fn fsync(&self, _file: usize) -> Result<usize> {
Ok(()) Ok(0)
} }
fn close(&self, _file: usize) -> Result<()> { fn close(&self, _file: usize) -> Result<usize> {
Ok(()) Ok(0)
} }
} }

View file

@ -13,7 +13,8 @@ use collections::BTreeMap;
use spin::{Once, RwLock, RwLockReadGuard, RwLockWriteGuard}; use spin::{Once, RwLock, RwLockReadGuard, RwLockWriteGuard};
use syscall::{Error, Result}; use syscall::error::*;
use syscall::scheme::Scheme;
use self::debug::DebugScheme; use self::debug::DebugScheme;
use self::env::EnvScheme; use self::env::EnvScheme;
@ -75,7 +76,7 @@ impl SchemeList {
/// Create a new scheme. /// Create a new scheme.
pub fn insert(&mut self, name: Box<[u8]>, scheme: Arc<Box<Scheme + Send + Sync>>) -> Result<&Arc<Box<Scheme + Send + Sync>>> { pub fn insert(&mut self, name: Box<[u8]>, scheme: Arc<Box<Scheme + Send + Sync>>) -> Result<&Arc<Box<Scheme + Send + Sync>>> {
if self.names.contains_key(&name) { if self.names.contains_key(&name) {
return Err(Error::FileExists); return Err(Error::new(EEXIST));
} }
if self.next_id >= SCHEME_MAX_SCHEMES { if self.next_id >= SCHEME_MAX_SCHEMES {
@ -87,7 +88,7 @@ impl SchemeList {
} }
if self.next_id >= SCHEME_MAX_SCHEMES { if self.next_id >= SCHEME_MAX_SCHEMES {
return Err(Error::TryAgain); return Err(Error::new(EAGAIN));
} }
let id = self.next_id; let id = self.next_id;
@ -123,32 +124,3 @@ pub fn schemes() -> RwLockReadGuard<'static, SchemeList> {
pub fn schemes_mut() -> RwLockWriteGuard<'static, SchemeList> { pub fn schemes_mut() -> RwLockWriteGuard<'static, SchemeList> {
SCHEMES.call_once(init_schemes).write() SCHEMES.call_once(init_schemes).write()
} }
/// A scheme trait, implemented by a scheme handler
pub trait Scheme {
/// Open the file at `path` with `flags`.
///
/// Returns a file descriptor or an error
fn open(&self, path: &[u8], flags: usize) -> Result<usize>;
/// Duplicate an open file descriptor
///
/// Returns a file descriptor or an error
fn dup(&self, file: usize) -> Result<usize>;
/// Read from some file descriptor into the `buffer`
///
/// Returns the number of bytes read
fn read(&self, file: usize, buffer: &mut [u8]) -> Result<usize>;
/// Write the `buffer` to the file descriptor
///
/// Returns the number of bytes written
fn write(&self, file: usize, buffer: &[u8]) -> Result<usize>;
/// Sync the file descriptor
fn fsync(&self, file: usize) -> Result<()>;
/// Close the file descriptor
fn close(&self, file: usize) -> Result<()>;
}

View file

@ -5,8 +5,9 @@ use core::sync::atomic::{AtomicUsize, Ordering};
use spin::RwLock; use spin::RwLock;
use context; use context;
use syscall::{Error, Result}; use syscall::error::*;
use scheme::{self, Scheme}; use syscall::scheme::Scheme;
use scheme;
use scheme::user::{UserInner, UserScheme}; use scheme::user::{UserInner, UserScheme};
pub struct RootScheme { pub struct RootScheme {
@ -27,14 +28,14 @@ impl Scheme for RootScheme {
fn open(&self, path: &[u8], _flags: usize) -> Result<usize> { fn open(&self, path: &[u8], _flags: usize) -> Result<usize> {
let context = { let context = {
let contexts = context::contexts(); let contexts = context::contexts();
let context = contexts.current().ok_or(Error::NoProcess)?; let context = contexts.current().ok_or(Error::new(ESRCH))?;
Arc::downgrade(&context) Arc::downgrade(&context)
}; };
let inner = { let inner = {
let mut schemes = scheme::schemes_mut(); let mut schemes = scheme::schemes_mut();
if schemes.get_name(path).is_some() { if schemes.get_name(path).is_some() {
return Err(Error::FileExists); return Err(Error::new(EEXIST));
} }
let inner = Arc::new(UserInner::new(context)); let inner = Arc::new(UserInner::new(context));
schemes.insert(path.to_vec().into_boxed_slice(), Arc::new(Box::new(UserScheme::new(Arc::downgrade(&inner))))).expect("failed to insert user scheme"); schemes.insert(path.to_vec().into_boxed_slice(), Arc::new(Box::new(UserScheme::new(Arc::downgrade(&inner))))).expect("failed to insert user scheme");
@ -50,7 +51,7 @@ impl Scheme for RootScheme {
fn dup(&self, file: usize) -> Result<usize> { fn dup(&self, file: usize) -> Result<usize> {
let mut handles = self.handles.write(); let mut handles = self.handles.write();
let inner = { let inner = {
let inner = handles.get(&file).ok_or(Error::BadFile)?; let inner = handles.get(&file).ok_or(Error::new(EBADF))?;
inner.clone() inner.clone()
}; };
@ -63,7 +64,7 @@ impl Scheme for RootScheme {
fn read(&self, file: usize, buf: &mut [u8]) -> Result<usize> { fn read(&self, file: usize, buf: &mut [u8]) -> Result<usize> {
let inner = { let inner = {
let handles = self.handles.read(); let handles = self.handles.read();
let inner = handles.get(&file).ok_or(Error::BadFile)?; let inner = handles.get(&file).ok_or(Error::new(EBADF))?;
inner.clone() inner.clone()
}; };
@ -73,18 +74,18 @@ impl Scheme for RootScheme {
fn write(&self, file: usize, buf: &[u8]) -> Result<usize> { fn write(&self, file: usize, buf: &[u8]) -> Result<usize> {
let inner = { let inner = {
let handles = self.handles.read(); let handles = self.handles.read();
let inner = handles.get(&file).ok_or(Error::BadFile)?; let inner = handles.get(&file).ok_or(Error::new(EBADF))?;
inner.clone() inner.clone()
}; };
inner.write(buf) inner.write(buf)
} }
fn fsync(&self, _file: usize) -> Result<()> { fn fsync(&self, _file: usize) -> Result<usize> {
Ok(()) Ok(0)
} }
fn close(&self, file: usize) -> Result<()> { fn close(&self, file: usize) -> Result<usize> {
self.handles.write().remove(&file).ok_or(Error::BadFile).and(Ok(())) self.handles.write().remove(&file).ok_or(Error::new(EBADF)).and(Ok(0))
} }
} }

View file

@ -9,9 +9,9 @@ use arch::paging::{InactivePageTable, Page, VirtualAddress, entry};
use arch::paging::temporary_page::TemporaryPage; use arch::paging::temporary_page::TemporaryPage;
use context::{self, Context}; use context::{self, Context};
use context::memory::Grant; use context::memory::Grant;
use syscall::{convert_to_result, Call, Error, Result}; use syscall::error::*;
use syscall::number::*;
use super::Scheme; use syscall::scheme::Scheme;
#[derive(Copy, Clone, Debug, Default)] #[derive(Copy, Clone, Debug, Default)]
#[repr(packed)] #[repr(packed)]
@ -40,12 +40,12 @@ impl UserInner {
} }
} }
pub fn call(&self, a: Call, b: usize, c: usize, d: usize) -> Result<usize> { pub fn call(&self, a: usize, b: usize, c: usize, d: usize) -> Result<usize> {
let id = self.next_id.fetch_add(1, Ordering::SeqCst); let id = self.next_id.fetch_add(1, Ordering::SeqCst);
let packet = Packet { let packet = Packet {
id: id, id: id,
a: a as usize, a: a,
b: b, b: b,
c: c, c: c,
d: d d: d
@ -57,7 +57,7 @@ impl UserInner {
{ {
let mut done = self.done.lock(); let mut done = self.done.lock();
if let Some(a) = done.remove(&id) { if let Some(a) = done.remove(&id) {
return convert_to_result(a); return Error::demux(a);
} }
} }
@ -74,7 +74,7 @@ impl UserInner {
} }
fn capture_inner(&self, address: usize, size: usize, writable: bool) -> Result<usize> { fn capture_inner(&self, address: usize, size: usize, writable: bool) -> Result<usize> {
let context_lock = self.context.upgrade().ok_or(Error::NoProcess)?; let context_lock = self.context.upgrade().ok_or(Error::new(ESRCH))?;
let context = context_lock.read(); let context = context_lock.read();
let mut grants = context.grants.lock(); let mut grants = context.grants.lock();
@ -125,7 +125,7 @@ impl UserInner {
} }
pub fn release(&self, address: usize) -> Result<()> { pub fn release(&self, address: usize) -> Result<()> {
let context_lock = self.context.upgrade().ok_or(Error::NoProcess)?; let context_lock = self.context.upgrade().ok_or(Error::new(ESRCH))?;
let context = context_lock.read(); let context = context_lock.read();
let mut grants = context.grants.lock(); let mut grants = context.grants.lock();
@ -143,7 +143,7 @@ impl UserInner {
} }
} }
Err(Error::Fault) Err(Error::new(EFAULT))
} }
pub fn read(&self, buf: &mut [u8]) -> Result<usize> { pub fn read(&self, buf: &mut [u8]) -> Result<usize> {
@ -201,41 +201,41 @@ impl UserScheme {
impl Scheme for UserScheme { impl Scheme for UserScheme {
fn open(&self, path: &[u8], flags: usize) -> Result<usize> { fn open(&self, path: &[u8], flags: usize) -> Result<usize> {
let inner = self.inner.upgrade().ok_or(Error::NoDevice)?; let inner = self.inner.upgrade().ok_or(Error::new(ENODEV))?;
let address = inner.capture(path)?; let address = inner.capture(path)?;
let result = inner.call(Call::Open, address, path.len(), flags); let result = inner.call(SYS_OPEN, address, path.len(), flags);
let _ = inner.release(address); let _ = inner.release(address);
result result
} }
fn dup(&self, file: usize) -> Result<usize> { fn dup(&self, file: usize) -> Result<usize> {
let inner = self.inner.upgrade().ok_or(Error::NoDevice)?; let inner = self.inner.upgrade().ok_or(Error::new(ENODEV))?;
inner.call(Call::Dup, file, 0, 0) inner.call(SYS_DUP, file, 0, 0)
} }
fn read(&self, file: usize, buf: &mut [u8]) -> Result<usize> { fn read(&self, file: usize, buf: &mut [u8]) -> Result<usize> {
let inner = self.inner.upgrade().ok_or(Error::NoDevice)?; let inner = self.inner.upgrade().ok_or(Error::new(ENODEV))?;
let address = inner.capture_mut(buf)?; let address = inner.capture_mut(buf)?;
let result = inner.call(Call::Read, file, address, buf.len()); let result = inner.call(SYS_READ, file, address, buf.len());
let _ = inner.release(address); let _ = inner.release(address);
result result
} }
fn write(&self, file: usize, buf: &[u8]) -> Result<usize> { fn write(&self, file: usize, buf: &[u8]) -> Result<usize> {
let inner = self.inner.upgrade().ok_or(Error::NoDevice)?; let inner = self.inner.upgrade().ok_or(Error::new(ENODEV))?;
let address = inner.capture(buf)?; let address = inner.capture(buf)?;
let result = inner.call(Call::Write, file, buf.as_ptr() as usize, buf.len()); let result = inner.call(SYS_WRITE, file, buf.as_ptr() as usize, buf.len());
let _ = inner.release(address); let _ = inner.release(address);
result result
} }
fn fsync(&self, file: usize) -> Result<()> { fn fsync(&self, file: usize) -> Result<usize> {
let inner = self.inner.upgrade().ok_or(Error::NoDevice)?; let inner = self.inner.upgrade().ok_or(Error::new(ENODEV))?;
inner.call(Call::FSync, file, 0, 0).and(Ok(())) inner.call(SYS_FSYNC, file, 0, 0)
} }
fn close(&self, file: usize) -> Result<()> { fn close(&self, file: usize) -> Result<usize> {
let inner = self.inner.upgrade().ok_or(Error::NoDevice)?; let inner = self.inner.upgrade().ok_or(Error::new(ENODEV))?;
inner.call(Call::Close, file, 0, 0).and(Ok(())) inner.call(SYS_CLOSE, file, 0, 0)
} }
} }

View file

@ -1,64 +0,0 @@
/// System call list
/// See http://syscalls.kernelgrok.com/ for numbers
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
#[repr(C)]
pub enum Call {
/// Exit syscall
Exit = 1,
/// Read syscall
Read = 3,
/// Write syscall
Write = 4,
/// Open syscall
Open = 5,
/// Close syscall
Close = 6,
/// Wait for a process
WaitPid = 7,
/// Execute syscall
Exec = 11,
/// Change working directory
ChDir = 12,
/// Get process ID
GetPid = 20,
/// Duplicate file descriptor
Dup = 41,
/// Set process break
Brk = 45,
/// Set process I/O privilege level
Iopl = 110,
/// Sync file descriptor
FSync = 118,
/// Clone process
Clone = 120,
/// Yield to scheduler
SchedYield = 158,
/// Get process working directory
GetCwd = 183
}
/// Convert numbers to calls
/// See http://syscalls.kernelgrok.com/
impl Call {
pub fn from(number: usize) -> Option<Call> {
match number {
1 => Some(Call::Exit),
3 => Some(Call::Read),
4 => Some(Call::Write),
5 => Some(Call::Open),
6 => Some(Call::Close),
7 => Some(Call::WaitPid),
11 => Some(Call::Exec),
12 => Some(Call::ChDir),
20 => Some(Call::GetPid),
41 => Some(Call::Dup),
45 => Some(Call::Brk),
110 => Some(Call::Iopl),
118 => Some(Call::FSync),
120 => Some(Call::Clone),
158 => Some(Call::SchedYield),
183 => Some(Call::GetCwd),
_ => None
}
}
}

View file

@ -1,63 +0,0 @@
/// The error number for an invalid value
/// See http://www-numi.fnal.gov/offline_software/srt_public_context/WebDocs/Errors/unix_system_errors.html for numbers
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
#[repr(C)]
pub enum Error {
/// Operation not permitted
NotPermitted = 1,
/// No such file or directory
NoEntry = 2,
/// No such process
NoProcess = 3,
/// Invalid executable format
NoExec = 8,
/// Bad file number
BadFile = 9,
/// Try again
TryAgain = 11,
/// Bad address
Fault = 14,
/// File exists
FileExists = 17,
/// No such device
NoDevice = 19,
/// Invalid argument
InvalidValue = 22,
/// Too many open files
TooManyFiles = 24,
/// Illegal seek
IllegalSeek = 29,
/// Syscall not implemented
NoCall = 38
}
impl Error {
pub fn from(number: usize) -> Option<Error> {
match number {
1 => Some(Error::NotPermitted),
2 => Some(Error::NoEntry),
3 => Some(Error::NoProcess),
8 => Some(Error::NoExec),
9 => Some(Error::BadFile),
11 => Some(Error::TryAgain),
14 => Some(Error::Fault),
17 => Some(Error::FileExists),
19 => Some(Error::NoDevice),
22 => Some(Error::InvalidValue),
24 => Some(Error::TooManyFiles),
29 => Some(Error::IllegalSeek),
38 => Some(Error::NoCall),
_ => None
}
}
}
pub type Result<T> = ::core::result::Result<T, Error>;
pub fn convert_to_result(number: usize) -> Result<usize> {
if let Some(err) = Error::from((-(number as isize)) as usize) {
Err(err)
} else {
Ok(number)
}
}

View file

@ -2,13 +2,12 @@
use context; use context;
use scheme; use scheme;
use syscall::error::*;
use super::{Error, Result};
/// Change the current working directory /// Change the current working directory
pub fn chdir(path: &[u8]) -> Result<usize> { pub fn chdir(path: &[u8]) -> Result<usize> {
let contexts = context::contexts(); let contexts = context::contexts();
let context_lock = contexts.current().ok_or(Error::NoProcess)?; let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
let context = context_lock.read(); let context = context_lock.read();
let canonical = context.canonicalize(path); let canonical = context.canonicalize(path);
*context.cwd.lock() = canonical; *context.cwd.lock() = canonical;
@ -18,7 +17,7 @@ pub fn chdir(path: &[u8]) -> Result<usize> {
/// Get the current working directory /// Get the current working directory
pub fn getcwd(buf: &mut [u8]) -> Result<usize> { pub fn getcwd(buf: &mut [u8]) -> Result<usize> {
let contexts = context::contexts(); let contexts = context::contexts();
let context_lock = contexts.current().ok_or(Error::NoProcess)?; let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
let context = context_lock.read(); let context = context_lock.read();
let cwd = context.cwd.lock(); let cwd = context.cwd.lock();
let mut i = 0; let mut i = 0;
@ -33,7 +32,7 @@ pub fn getcwd(buf: &mut [u8]) -> Result<usize> {
pub fn open(path: &[u8], flags: usize) -> Result<usize> { pub fn open(path: &[u8], flags: usize) -> Result<usize> {
let path_canon = { let path_canon = {
let contexts = context::contexts(); let contexts = context::contexts();
let context_lock = contexts.current().ok_or(Error::NoProcess)?; let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
let context = context_lock.read(); let context = context_lock.read();
context.canonicalize(path) context.canonicalize(path)
}; };
@ -43,10 +42,10 @@ pub fn open(path: &[u8], flags: usize) -> Result<usize> {
let reference_opt = parts.next(); let reference_opt = parts.next();
let (scheme_id, file_id) = { let (scheme_id, file_id) = {
let namespace = namespace_opt.ok_or(Error::NoEntry)?; let namespace = namespace_opt.ok_or(Error::new(ENOENT))?;
let (scheme_id, scheme) = { let (scheme_id, scheme) = {
let schemes = scheme::schemes(); let schemes = scheme::schemes();
let (scheme_id, scheme) = schemes.get_name(namespace).ok_or(Error::NoEntry)?; let (scheme_id, scheme) = schemes.get_name(namespace).ok_or(Error::new(ENOENT))?;
(scheme_id, scheme.clone()) (scheme_id, scheme.clone())
}; };
let file_id = scheme.open(reference_opt.unwrap_or(b""), flags)?; let file_id = scheme.open(reference_opt.unwrap_or(b""), flags)?;
@ -54,105 +53,100 @@ pub fn open(path: &[u8], flags: usize) -> Result<usize> {
}; };
let contexts = context::contexts(); let contexts = context::contexts();
let context_lock = contexts.current().ok_or(Error::NoProcess)?; let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
let context = context_lock.read(); let context = context_lock.read();
context.add_file(::context::file::File { context.add_file(::context::file::File {
scheme: scheme_id, scheme: scheme_id,
number: file_id number: file_id
}).ok_or(Error::TooManyFiles) }).ok_or(Error::new(EMFILE))
} }
/// Close syscall /// Close syscall
pub fn close(fd: usize) -> Result<usize> { pub fn close(fd: usize) -> Result<usize> {
let file = { let file = {
let contexts = context::contexts(); let contexts = context::contexts();
let context_lock = contexts.current().ok_or(Error::NoProcess)?; let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
let context = context_lock.read(); let context = context_lock.read();
let file = context.remove_file(fd).ok_or(Error::BadFile)?; let file = context.remove_file(fd).ok_or(Error::new(EBADF))?;
file file
}; };
let scheme = { let scheme = {
let schemes = scheme::schemes(); let schemes = scheme::schemes();
let scheme = schemes.get(file.scheme).ok_or(Error::BadFile)?; let scheme = schemes.get(file.scheme).ok_or(Error::new(EBADF))?;
scheme.clone() scheme.clone()
}; };
let result = scheme.close(file.number).and(Ok(0)); scheme.close(file.number)
result
} }
/// Duplicate file descriptor /// Duplicate file descriptor
pub fn dup(fd: usize) -> Result<usize> { pub fn dup(fd: usize) -> Result<usize> {
let file = { let file = {
let contexts = context::contexts(); let contexts = context::contexts();
let context_lock = contexts.current().ok_or(Error::NoProcess)?; let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
let context = context_lock.read(); let context = context_lock.read();
let file = context.get_file(fd).ok_or(Error::BadFile)?; let file = context.get_file(fd).ok_or(Error::new(EBADF))?;
file file
}; };
let scheme = { let scheme = {
let schemes = scheme::schemes(); let schemes = scheme::schemes();
let scheme = schemes.get(file.scheme).ok_or(Error::BadFile)?; let scheme = schemes.get(file.scheme).ok_or(Error::new(EBADF))?;
scheme.clone() scheme.clone()
}; };
let result = scheme.dup(file.number); scheme.dup(file.number)
result
} }
/// Sync the file descriptor /// Sync the file descriptor
pub fn fsync(fd: usize) -> Result<usize> { pub fn fsync(fd: usize) -> Result<usize> {
let file = { let file = {
let contexts = context::contexts(); let contexts = context::contexts();
let context_lock = contexts.current().ok_or(Error::NoProcess)?; let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
let context = context_lock.read(); let context = context_lock.read();
let file = context.get_file(fd).ok_or(Error::BadFile)?; let file = context.get_file(fd).ok_or(Error::new(EBADF))?;
file file
}; };
let scheme = { let scheme = {
let schemes = scheme::schemes(); let schemes = scheme::schemes();
let scheme = schemes.get(file.scheme).ok_or(Error::BadFile)?; let scheme = schemes.get(file.scheme).ok_or(Error::new(EBADF))?;
scheme.clone() scheme.clone()
}; };
let result = scheme.fsync(file.number).and(Ok(0)); scheme.fsync(file.number)
result
} }
/// Read syscall /// Read syscall
pub fn read(fd: usize, buf: &mut [u8]) -> Result<usize> { pub fn read(fd: usize, buf: &mut [u8]) -> Result<usize> {
let file = { let file = {
let contexts = context::contexts(); let contexts = context::contexts();
let context_lock = contexts.current().ok_or(Error::NoProcess)?; let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
let context = context_lock.read(); let context = context_lock.read();
let file = context.get_file(fd).ok_or(Error::BadFile)?; let file = context.get_file(fd).ok_or(Error::new(EBADF))?;
file file
}; };
let scheme = { let scheme = {
let schemes = scheme::schemes(); let schemes = scheme::schemes();
let scheme = schemes.get(file.scheme).ok_or(Error::BadFile)?; let scheme = schemes.get(file.scheme).ok_or(Error::new(EBADF))?;
scheme.clone() scheme.clone()
}; };
let result = scheme.read(file.number, buf); scheme.read(file.number, buf)
result
} }
/// Write syscall /// Write syscall
pub fn write(fd: usize, buf: &[u8]) -> Result<usize> { pub fn write(fd: usize, buf: &[u8]) -> Result<usize> {
let file = { let file = {
let contexts = context::contexts(); let contexts = context::contexts();
let context_lock = contexts.current().ok_or(Error::NoProcess)?; let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
let context = context_lock.read(); let context = context_lock.read();
let file = context.get_file(fd).ok_or(Error::BadFile)?; let file = context.get_file(fd).ok_or(Error::new(EBADF))?;
file file
}; };
let scheme = { let scheme = {
let schemes = scheme::schemes(); let schemes = scheme::schemes();
let scheme = schemes.get(file.scheme).ok_or(Error::BadFile)?; let scheme = schemes.get(file.scheme).ok_or(Error::new(EBADF))?;
scheme.clone() scheme.clone()
}; };
let result = scheme.write(file.number, buf); scheme.write(file.number, buf)
result
} }

View file

@ -1,60 +1,51 @@
///! Syscall handlers ///! Syscall handlers
pub use self::call::*; extern crate syscall;
pub use self::error::*;
pub use self::syscall::{error, number, scheme};
use self::error::{Error, Result, ENOSYS};
use self::number::*;
pub use self::fs::*; pub use self::fs::*;
pub use self::process::*; pub use self::process::*;
pub use self::validate::*; pub use self::validate::*;
/// System call numbers
mod call;
/// System error codes
mod error;
/// Filesystem syscalls /// Filesystem syscalls
mod fs; pub mod fs;
/// Process syscalls /// Process syscalls
mod process; pub mod process;
/// Validate input /// Validate input
mod validate; pub mod validate;
#[no_mangle] #[no_mangle]
pub extern fn syscall(a: usize, b: usize, c: usize, d: usize, e: usize, f: usize, stack: usize) -> usize { pub extern fn syscall(a: usize, b: usize, c: usize, d: usize, e: usize, f: usize, stack: usize) -> usize {
#[inline(always)] #[inline(always)]
fn inner(a: usize, b: usize, c: usize, d: usize, e: usize, _f: usize, stack: usize) -> Result<usize> { fn inner(a: usize, b: usize, c: usize, d: usize, e: usize, _f: usize, stack: usize) -> Result<usize> {
//println!("{}: {:?}: {} {} {} {}", ::context::context_id(), Call::from(a), a, b, c, d); match a {
SYS_EXIT => exit(b),
match Call::from(a) { SYS_READ => read(b, validate_slice_mut(c as *mut u8, d)?),
Some(call) => match call { SYS_WRITE => write(b, validate_slice(c as *const u8, d)?),
Call::Exit => exit(b), SYS_OPEN => open(validate_slice(b as *const u8, c)?, d),
Call::Read => read(b, validate_slice_mut(c as *mut u8, d)?), SYS_CLOSE => close(b),
Call::Write => write(b, validate_slice(c as *const u8, d)?), SYS_WAITPID => waitpid(b, c, d),
Call::Open => open(validate_slice(b as *const u8, c)?, d), SYS_EXECVE => exec(validate_slice(b as *const u8, c)?, validate_slice(d as *const [usize; 2], e)?),
Call::Close => close(b), SYS_CHDIR => chdir(validate_slice(b as *const u8, c)?),
Call::WaitPid => waitpid(b, c, d), SYS_GETPID => getpid(),
Call::Exec => exec(validate_slice(b as *const u8, c)?, validate_slice(d as *const [usize; 2], e)?), SYS_DUP => dup(b),
Call::ChDir => chdir(validate_slice(b as *const u8, c)?), SYS_BRK => brk(b),
Call::GetPid => getpid(), SYS_IOPL => iopl(b),
Call::Dup => dup(b), SYS_FSYNC => fsync(b),
Call::Brk => brk(b), SYS_CLONE => clone(b, stack),
Call::Iopl => iopl(b), SYS_YIELD => sched_yield(),
Call::FSync => fsync(b), SYS_GETCWD => getcwd(validate_slice_mut(b as *mut u8, c)?),
Call::Clone => clone(b, stack), _ => {
Call::SchedYield => sched_yield(),
Call::GetCwd => getcwd(validate_slice_mut(b as *mut u8, c)?)
},
None => {
println!("Unknown syscall {}", a); println!("Unknown syscall {}", a);
Err(Error::NoCall) Err(Error::new(ENOSYS))
} }
} }
} }
match inner(a, b, c, d, e, f, stack) { Error::mux(inner(a, b, c, d, e, f, stack))
Ok(value) => value,
Err(value) => (-(value as isize)) as usize
}
} }

View file

@ -15,11 +15,13 @@ use arch::start::usermode;
use context; use context;
use elf::{self, program_header}; use elf::{self, program_header};
use scheme; use scheme;
use syscall::{self, Error, Result, validate_slice, validate_slice_mut}; use syscall;
use syscall::error::*;
use syscall::validate::{validate_slice, validate_slice_mut};
pub fn brk(address: usize) -> Result<usize> { pub fn brk(address: usize) -> Result<usize> {
let contexts = context::contexts(); let contexts = context::contexts();
let context_lock = contexts.current().ok_or(Error::NoProcess)?; let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
let context = context_lock.read(); let context = context_lock.read();
let current = if let Some(ref heap_shared) = context.heap { let current = if let Some(ref heap_shared) = context.heap {
@ -45,8 +47,7 @@ pub fn brk(address: usize) -> Result<usize> {
Ok(address) Ok(address)
} else { } else {
//TODO: Return correct error Err(Error::new(ENOMEM))
Err(Error::NotPermitted)
} }
} }
@ -75,7 +76,7 @@ pub fn clone(flags: usize, stack_base: usize) -> Result<usize> {
// Copy from old process // Copy from old process
{ {
let contexts = context::contexts(); let contexts = context::contexts();
let context_lock = contexts.current().ok_or(Error::NoProcess)?; let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
let context = context_lock.read(); let context = context_lock.read();
ppid = context.id; ppid = context.id;
@ -186,7 +187,7 @@ pub fn clone(flags: usize, stack_base: usize) -> Result<usize> {
let result = { let result = {
let scheme = { let scheme = {
let schemes = scheme::schemes(); let schemes = scheme::schemes();
let scheme = schemes.get(file.scheme).ok_or(Error::BadFile)?; let scheme = schemes.get(file.scheme).ok_or(Error::new(EBADF))?;
scheme.clone() scheme.clone()
}; };
let result = scheme.dup(file.number); let result = scheme.dup(file.number);
@ -377,7 +378,7 @@ pub fn exec(path: &[u8], arg_ptrs: &[[usize; 2]]) -> Result<usize> {
drop(arg_ptrs); // Drop so that usage is not allowed after unmapping context drop(arg_ptrs); // Drop so that usage is not allowed after unmapping context
let contexts = context::contexts(); let contexts = context::contexts();
let context_lock = contexts.current().ok_or(Error::NoProcess)?; let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
let mut context = context_lock.write(); let mut context = context_lock.write();
// Unmap previous image and stack // Unmap previous image and stack
@ -478,7 +479,7 @@ pub fn exec(path: &[u8], arg_ptrs: &[[usize; 2]]) -> Result<usize> {
}, },
Err(err) => { Err(err) => {
println!("failed to execute {}: {}", unsafe { str::from_utf8_unchecked(path) }, err); println!("failed to execute {}: {}", unsafe { str::from_utf8_unchecked(path) }, err);
return Err(Error::NoExec); return Err(Error::new(ENOEXEC));
} }
} }
} }
@ -489,7 +490,7 @@ pub fn exec(path: &[u8], arg_ptrs: &[[usize; 2]]) -> Result<usize> {
pub fn getpid() -> Result<usize> { pub fn getpid() -> Result<usize> {
let contexts = context::contexts(); let contexts = context::contexts();
let context_lock = contexts.current().ok_or(Error::NoProcess)?; let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
let context = context_lock.read(); let context = context_lock.read();
Ok(context.id) Ok(context.id)
} }
@ -512,7 +513,7 @@ pub fn waitpid(pid: usize, status_ptr: usize, _options: usize) -> Result<usize>
{ {
let contexts = context::contexts(); let contexts = context::contexts();
let context_lock = contexts.get(pid).ok_or(Error::NoProcess)?; let context_lock = contexts.get(pid).ok_or(Error::new(ESRCH))?;
let context = context_lock.read(); let context = context_lock.read();
if let context::Status::Exited(status) = context.status { if let context::Status::Exited(status) = context.status {
if status_ptr != 0 { if status_ptr != 0 {
@ -525,7 +526,7 @@ pub fn waitpid(pid: usize, status_ptr: usize, _options: usize) -> Result<usize>
if exited { if exited {
let mut contexts = context::contexts_mut(); let mut contexts = context::contexts_mut();
return contexts.remove(pid).ok_or(Error::NoProcess).and(Ok(pid)); return contexts.remove(pid).ok_or(Error::new(ESRCH)).and(Ok(pid));
} }
} }

View file

@ -1,6 +1,6 @@
use core::slice; use core::slice;
use super::Result; use syscall::error::*;
/// Convert a pointer and length to slice, if valid /// Convert a pointer and length to slice, if valid
/// TODO: Check validity /// TODO: Check validity

View file

@ -24,6 +24,6 @@ fn stdio() {
/// Test that invalid reads/writes cause errors /// Test that invalid reads/writes cause errors
#[test] #[test]
fn invalid_path() { fn invalid_path() {
assert_eq!(syscall::read(999, &mut []), Err(Error::BadFile)); assert_eq!(syscall::read(999, &mut []), Err(Error::new(EBADF)));
assert_eq!(syscall::write(999, &[]), Err(Error::BadFile)); assert_eq!(syscall::write(999, &[]), Err(Error::new(EBADF)));
} }

View file

@ -0,0 +1,6 @@
[package]
name = "example"
version = "0.1.0"
[dependencies.syscall]
path = "../../syscall/"

View file

@ -0,0 +1,38 @@
extern crate syscall;
use std::fs::File;
use std::io::{Read, Write};
use std::str;
use std::thread;
use syscall::{Packet, Result, Scheme};
struct ExampleScheme;
impl Scheme for ExampleScheme {
fn open(&self, path: &[u8], _flags: usize) -> Result<usize> {
println!("{}", unsafe { str::from_utf8_unchecked(path) });
Ok(0)
}
fn dup(&self, file: usize) -> Result<usize> {
Ok(file)
}
fn close(&self, _file: usize) -> Result<usize> {
Ok(0)
}
}
fn main(){
thread::spawn(move || {
let mut socket = File::create(":example").expect("example: failed to create example scheme");
let scheme = ExampleScheme;
loop {
let mut packet = Packet::default();
socket.read(&mut packet).expect("example: failed to read events from example scheme");
scheme.handle(&mut packet);
socket.write(&packet).expect("example: failed to write responses to example scheme");
}
});
}

View file

@ -1,5 +1,6 @@
use core::{fmt, result}; use core::{fmt, result};
#[derive(Eq, PartialEq)]
pub struct Error { pub struct Error {
pub errno: isize, pub errno: isize,
} }

View file

@ -3,6 +3,7 @@
pub use self::arch::*; pub use self::arch::*;
pub use self::error::*; pub use self::error::*;
pub use self::number::*;
pub use self::scheme::*; pub use self::scheme::*;
#[cfg(target_arch = "x86")] #[cfg(target_arch = "x86")]
@ -13,74 +14,52 @@ mod arch;
#[path="x86_64.rs"] #[path="x86_64.rs"]
mod arch; mod arch;
mod error; pub mod error;
mod scheme; pub mod number;
pub const SYS_BRK: usize = 45; pub mod scheme;
pub const SYS_CHDIR: usize = 12;
pub const SYS_CLONE: usize = 120; pub const CLONE_VM: usize = 0x100;
pub const CLONE_VM: usize = 0x100; pub const CLONE_FS: usize = 0x200;
pub const CLONE_FS: usize = 0x200; pub const CLONE_FILES: usize = 0x400;
pub const CLONE_FILES: usize = 0x400; pub const CLONE_VFORK: usize = 0x4000;
pub const CLONE_VFORK: usize = 0x4000; /// Mark this clone as supervised.
/// Mark this clone as supervised. ///
/// /// This means that the process can run in supervised mode, even not being connected to
/// This means that the process can run in supervised mode, even not being connected to /// a supervisor yet. In other words, the parent can later on supervise the process and handle
/// a supervisor yet. In other words, the parent can later on supervise the process and handle /// the potential blocking syscall.
/// the potential blocking syscall. ///
/// /// This is an important security measure, since otherwise the process would be able to fork it
/// This is an important security measure, since otherwise the process would be able to fork it /// self right after starting, making supervising it impossible.
/// self right after starting, making supervising it impossible. pub const CLONE_SUPERVISE: usize = 0x400000;
pub const CLONE_SUPERVISE: usize = 0x400000; pub const CLOCK_REALTIME: usize = 1;
pub const SYS_CLOSE: usize = 6; pub const CLOCK_MONOTONIC: usize = 4;
pub const SYS_CLOCK_GETTIME: usize = 265;
pub const CLOCK_REALTIME: usize = 1; pub const MODE_DIR: u16 = 0x4000;
pub const CLOCK_MONOTONIC: usize = 4; pub const MODE_FILE: u16 = 0x8000;
pub const SYS_DUP: usize = 41; pub const MODE_ALL: u16 = MODE_DIR | MODE_FILE;
pub const SYS_EXECVE: usize = 11;
pub const SYS_EXIT: usize = 1; pub const FUTEX_WAIT: usize = 0;
pub const SYS_FPATH: usize = 928; pub const FUTEX_WAKE: usize = 1;
pub const SYS_FSTAT: usize = 28; pub const FUTEX_REQUEUE: usize = 2;
pub const MODE_DIR: u16 = 0x4000;
pub const MODE_FILE: u16 = 0x8000; pub const SEEK_SET: usize = 0;
pub const MODE_ALL: u16 = MODE_DIR | MODE_FILE; pub const SEEK_CUR: usize = 1;
pub const SYS_FSYNC: usize = 118; pub const SEEK_END: usize = 2;
pub const SYS_FTRUNCATE: usize = 93;
pub const SYS_FUTEX: usize = 240; pub const O_RDONLY: usize = 0;
pub const FUTEX_WAIT: usize = 0; pub const O_WRONLY: usize = 1;
pub const FUTEX_WAKE: usize = 1; pub const O_RDWR: usize = 2;
pub const FUTEX_REQUEUE: usize = 2; pub const O_NONBLOCK: usize = 4;
pub const SYS_GETCWD: usize = 183; pub const O_APPEND: usize = 8;
pub const SYS_GETPID: usize = 20; pub const O_SHLOCK: usize = 0x10;
pub const SYS_IOPL: usize = 110; pub const O_EXLOCK: usize = 0x20;
pub const SYS_LINK: usize = 9; pub const O_ASYNC: usize = 0x40;
pub const SYS_LSEEK: usize = 19; pub const O_FSYNC: usize = 0x80;
pub const SEEK_SET: usize = 0; pub const O_CREAT: usize = 0x200;
pub const SEEK_CUR: usize = 1; pub const O_TRUNC: usize = 0x400;
pub const SEEK_END: usize = 2; pub const O_EXCL: usize = 0x800;
pub const SYS_MKDIR: usize = 39;
pub const SYS_NANOSLEEP: usize = 162;
pub const SYS_OPEN: usize = 5;
pub const O_RDONLY: usize = 0;
pub const O_WRONLY: usize = 1;
pub const O_RDWR: usize = 2;
pub const O_NONBLOCK: usize = 4;
pub const O_APPEND: usize = 8;
pub const O_SHLOCK: usize = 0x10;
pub const O_EXLOCK: usize = 0x20;
pub const O_ASYNC: usize = 0x40;
pub const O_FSYNC: usize = 0x80;
pub const O_CREAT: usize = 0x200;
pub const O_TRUNC: usize = 0x400;
pub const O_EXCL: usize = 0x800;
pub const SYS_PIPE2: usize = 331;
pub const SYS_READ: usize = 3;
pub const SYS_RMDIR: usize = 84;
pub const SYS_UNLINK: usize = 10;
pub const SYS_WAITPID: usize = 7;
pub const SYS_WRITE: usize = 4;
pub const SYS_YIELD: usize = 158;
#[derive(Copy, Clone, Debug, Default)] #[derive(Copy, Clone, Debug, Default)]
#[repr(packed)] #[repr(packed)]

28
syscall/src/number.rs Normal file
View file

@ -0,0 +1,28 @@
pub const SYS_BRK: usize = 45;
pub const SYS_CHDIR: usize = 12;
pub const SYS_CLONE: usize = 120;
pub const SYS_CLOSE: usize = 6;
pub const SYS_CLOCK_GETTIME: usize = 265;
pub const SYS_DUP: usize = 41;
pub const SYS_EXECVE: usize = 11;
pub const SYS_EXIT: usize = 1;
pub const SYS_FPATH: usize = 928;
pub const SYS_FSTAT: usize = 28;
pub const SYS_FSYNC: usize = 118;
pub const SYS_FTRUNCATE: usize = 93;
pub const SYS_FUTEX: usize = 240;
pub const SYS_GETCWD: usize = 183;
pub const SYS_GETPID: usize = 20;
pub const SYS_IOPL: usize = 110;
pub const SYS_LINK: usize = 9;
pub const SYS_LSEEK: usize = 19;
pub const SYS_MKDIR: usize = 39;
pub const SYS_NANOSLEEP: usize = 162;
pub const SYS_OPEN: usize = 5;
pub const SYS_PIPE2: usize = 331;
pub const SYS_READ: usize = 3;
pub const SYS_RMDIR: usize = 84;
pub const SYS_UNLINK: usize = 10;
pub const SYS_WAITPID: usize = 7;
pub const SYS_WRITE: usize = 4;
pub const SYS_YIELD: usize = 158;

View file

@ -1,6 +1,8 @@
use core::ops::{Deref, DerefMut}; use core::ops::{Deref, DerefMut};
use core::{mem, slice}; use core::{mem, slice};
use super::*;
#[derive(Copy, Clone, Debug, Default)] #[derive(Copy, Clone, Debug, Default)]
#[repr(packed)] #[repr(packed)]
pub struct Packet { pub struct Packet {
@ -27,3 +29,99 @@ impl DerefMut for Packet {
} }
} }
} }
pub trait Scheme {
fn handle(&self, packet: &mut Packet) {
packet.a = Error::mux(match packet.a {
SYS_OPEN => self.open(unsafe { slice::from_raw_parts(packet.b as *const u8, packet.c) }, packet.d),
SYS_MKDIR => self.mkdir(unsafe { slice::from_raw_parts(packet.b as *const u8, packet.c) }, packet.d),
SYS_RMDIR => self.rmdir(unsafe { slice::from_raw_parts(packet.b as *const u8, packet.c) }),
SYS_UNLINK => self.unlink(unsafe { slice::from_raw_parts(packet.b as *const u8, packet.c) }),
SYS_DUP => self.dup(packet.b),
SYS_READ => self.read(packet.b, unsafe { slice::from_raw_parts_mut(packet.c as *mut u8, packet.d) }),
SYS_WRITE => self.write(packet.b, unsafe { slice::from_raw_parts(packet.c as *const u8, packet.d) }),
SYS_LSEEK => self.seek(packet.b, packet.c, packet.d),
SYS_FPATH => self.fpath(packet.b, unsafe { slice::from_raw_parts_mut(packet.c as *mut u8, packet.d) }),
SYS_FSTAT => self.fstat(packet.b, unsafe { &mut *(packet.c as *mut Stat) }),
SYS_FSYNC => self.fsync(packet.b),
SYS_FTRUNCATE => self.ftruncate(packet.b, packet.c),
SYS_CLOSE => self.close(packet.b),
_ => Err(Error::new(ENOSYS))
});
}
/* Scheme operations */
#[allow(unused_variables)]
fn open(&self, path: &[u8], flags: usize) -> Result<usize> {
Err(Error::new(ENOENT))
}
#[allow(unused_variables)]
fn mkdir(&self, path: &[u8], mode: usize) -> Result<usize> {
Err(Error::new(ENOENT))
}
#[allow(unused_variables)]
fn rmdir(&self, path: &[u8]) -> Result<usize> {
Err(Error::new(ENOENT))
}
#[allow(unused_variables)]
fn stat(&self, path: &[u8], stat: &mut Stat) -> Result<usize> {
Err(Error::new(ENOENT))
}
#[allow(unused_variables)]
fn unlink(&self, path: &[u8]) -> Result<usize> {
Err(Error::new(ENOENT))
}
/* Resource operations */
#[allow(unused_variables)]
fn dup(&self, old_id: usize) -> Result<usize> {
Err(Error::new(EBADF))
}
#[allow(unused_variables)]
fn read(&self, id: usize, buf: &mut [u8]) -> Result<usize> {
Err(Error::new(EBADF))
}
#[allow(unused_variables)]
fn write(&self, id: usize, buf: &[u8]) -> Result<usize> {
Err(Error::new(EBADF))
}
#[allow(unused_variables)]
fn seek(&self, id: usize, pos: usize, whence: usize) -> Result<usize> {
Err(Error::new(EBADF))
}
#[allow(unused_variables)]
fn fpath(&self, id: usize, buf: &mut [u8]) -> Result<usize> {
Err(Error::new(EBADF))
}
#[allow(unused_variables)]
fn fstat(&self, id: usize, stat: &mut Stat) -> Result<usize> {
Err(Error::new(EBADF))
}
#[allow(unused_variables)]
fn fsync(&self, id: usize) -> Result<usize> {
Err(Error::new(EBADF))
}
#[allow(unused_variables)]
fn ftruncate(&self, id: usize, len: usize) -> Result<usize> {
Err(Error::new(EBADF))
}
#[allow(unused_variables)]
fn close(&self, id: usize) -> Result<usize> {
Err(Error::new(EBADF))
}
}