Cleanup Redox repo, update Rust, remove old target
This commit is contained in:
parent
98c76d36fd
commit
7cd2eff74c
97 changed files with 24 additions and 79 deletions
130
kernel/src/syscall/driver.rs
Normal file
130
kernel/src/syscall/driver.rs
Normal file
|
@ -0,0 +1,130 @@
|
|||
use arch;
|
||||
use arch::memory::{allocate_frames, deallocate_frames, Frame};
|
||||
use arch::paging::{entry, ActivePageTable, PhysicalAddress, VirtualAddress};
|
||||
use context;
|
||||
use context::memory::Grant;
|
||||
use syscall::error::{Error, EFAULT, ENOMEM, EPERM, ESRCH, Result};
|
||||
use syscall::flag::{MAP_WRITE, MAP_WRITE_COMBINE};
|
||||
|
||||
fn enforce_root() -> Result<()> {
|
||||
let contexts = context::contexts();
|
||||
let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
|
||||
let context = context_lock.read();
|
||||
if context.euid == 0 {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::new(EPERM))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn iopl(_level: usize, _stack_base: usize) -> Result<usize> {
|
||||
enforce_root()?;
|
||||
|
||||
//TODO
|
||||
Ok(0)
|
||||
}
|
||||
|
||||
pub fn physalloc(size: usize) -> Result<usize> {
|
||||
enforce_root()?;
|
||||
|
||||
allocate_frames((size + 4095)/4096).ok_or(Error::new(ENOMEM)).map(|frame| frame.start_address().get())
|
||||
}
|
||||
|
||||
pub fn physfree(physical_address: usize, size: usize) -> Result<usize> {
|
||||
enforce_root()?;
|
||||
|
||||
deallocate_frames(Frame::containing_address(PhysicalAddress::new(physical_address)), (size + 4095)/4096);
|
||||
//TODO: Check that no double free occured
|
||||
Ok(0)
|
||||
}
|
||||
|
||||
//TODO: verify exlusive access to physical memory
|
||||
pub fn physmap(physical_address: usize, size: usize, flags: usize) -> Result<usize> {
|
||||
enforce_root()?;
|
||||
|
||||
if size == 0 {
|
||||
Ok(0)
|
||||
} else {
|
||||
let contexts = context::contexts();
|
||||
let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
|
||||
let context = context_lock.read();
|
||||
|
||||
let mut grants = context.grants.lock();
|
||||
|
||||
let from_address = (physical_address/4096) * 4096;
|
||||
let offset = physical_address - from_address;
|
||||
let full_size = ((offset + size + 4095)/4096) * 4096;
|
||||
let mut to_address = arch::USER_GRANT_OFFSET;
|
||||
|
||||
let mut entry_flags = entry::PRESENT | entry::NO_EXECUTE | entry::USER_ACCESSIBLE;
|
||||
if flags & MAP_WRITE == MAP_WRITE {
|
||||
entry_flags |= entry::WRITABLE;
|
||||
}
|
||||
if flags & MAP_WRITE_COMBINE == MAP_WRITE_COMBINE {
|
||||
entry_flags |= entry::HUGE_PAGE;
|
||||
}
|
||||
|
||||
for i in 0 .. grants.len() {
|
||||
let start = grants[i].start_address().get();
|
||||
if to_address + full_size < start {
|
||||
grants.insert(i, Grant::physmap(
|
||||
PhysicalAddress::new(from_address),
|
||||
VirtualAddress::new(to_address),
|
||||
full_size,
|
||||
entry_flags
|
||||
));
|
||||
|
||||
return Ok(to_address + offset);
|
||||
} else {
|
||||
let pages = (grants[i].size() + 4095) / 4096;
|
||||
let end = start + pages * 4096;
|
||||
to_address = end;
|
||||
}
|
||||
}
|
||||
|
||||
grants.push(Grant::physmap(
|
||||
PhysicalAddress::new(from_address),
|
||||
VirtualAddress::new(to_address),
|
||||
full_size,
|
||||
entry_flags
|
||||
));
|
||||
|
||||
Ok(to_address + offset)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn physunmap(virtual_address: usize) -> Result<usize> {
|
||||
enforce_root()?;
|
||||
|
||||
if virtual_address == 0 {
|
||||
Ok(0)
|
||||
} else {
|
||||
let contexts = context::contexts();
|
||||
let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
|
||||
let context = context_lock.read();
|
||||
|
||||
let mut grants = context.grants.lock();
|
||||
|
||||
for i in 0 .. grants.len() {
|
||||
let start = grants[i].start_address().get();
|
||||
let end = start + grants[i].size();
|
||||
if virtual_address >= start && virtual_address < end {
|
||||
grants.remove(i).unmap();
|
||||
|
||||
return Ok(0);
|
||||
}
|
||||
}
|
||||
|
||||
Err(Error::new(EFAULT))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn virttophys(virtual_address: usize) -> Result<usize> {
|
||||
enforce_root()?;
|
||||
|
||||
let active_table = unsafe { ActivePageTable::new() };
|
||||
match active_table.translate(VirtualAddress::new(virtual_address)) {
|
||||
Some(physical_address) => Ok(physical_address.get()),
|
||||
None => Err(Error::new(EFAULT))
|
||||
}
|
||||
}
|
356
kernel/src/syscall/fs.rs
Normal file
356
kernel/src/syscall/fs.rs
Normal file
|
@ -0,0 +1,356 @@
|
|||
//! Filesystem syscalls
|
||||
use core::sync::atomic::Ordering;
|
||||
|
||||
use context;
|
||||
use scheme::{self, FileHandle};
|
||||
use syscall;
|
||||
use syscall::data::{Packet, Stat};
|
||||
use syscall::error::*;
|
||||
use syscall::flag::{MODE_DIR, MODE_FILE};
|
||||
|
||||
pub fn file_op(a: usize, fd: FileHandle, c: usize, d: usize) -> Result<usize> {
|
||||
let (file, pid, uid, gid) = {
|
||||
let contexts = context::contexts();
|
||||
let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
|
||||
let context = context_lock.read();
|
||||
let file = context.get_file(fd).ok_or(Error::new(EBADF))?;
|
||||
(file, context.id, context.euid, context.egid)
|
||||
};
|
||||
|
||||
let scheme = {
|
||||
let schemes = scheme::schemes();
|
||||
let scheme = schemes.get(file.scheme).ok_or(Error::new(EBADF))?;
|
||||
scheme.clone()
|
||||
};
|
||||
|
||||
let mut packet = Packet {
|
||||
id: 0,
|
||||
pid: pid.into(),
|
||||
uid: uid,
|
||||
gid: gid,
|
||||
a: a,
|
||||
b: file.number,
|
||||
c: c,
|
||||
d: d
|
||||
};
|
||||
|
||||
scheme.handle(&mut packet);
|
||||
|
||||
Error::demux(packet.a)
|
||||
}
|
||||
|
||||
pub fn file_op_slice(a: usize, fd: FileHandle, slice: &[u8]) -> Result<usize> {
|
||||
file_op(a, fd, slice.as_ptr() as usize, slice.len())
|
||||
}
|
||||
|
||||
pub fn file_op_mut_slice(a: usize, fd: FileHandle, slice: &mut [u8]) -> Result<usize> {
|
||||
file_op(a, fd, slice.as_mut_ptr() as usize, slice.len())
|
||||
}
|
||||
|
||||
/// Change the current working directory
|
||||
pub fn chdir(path: &[u8]) -> Result<usize> {
|
||||
let fd = open(path, syscall::flag::O_RDONLY | syscall::flag::O_DIRECTORY)?;
|
||||
let mut stat = Stat::default();
|
||||
let stat_res = file_op_mut_slice(syscall::number::SYS_FSTAT, fd, &mut stat);
|
||||
let _ = close(fd);
|
||||
stat_res?;
|
||||
if stat.st_mode & (MODE_FILE | MODE_DIR) == MODE_DIR {
|
||||
let contexts = context::contexts();
|
||||
let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
|
||||
let context = context_lock.read();
|
||||
let canonical = context.canonicalize(path);
|
||||
*context.cwd.lock() = canonical;
|
||||
Ok(0)
|
||||
} else {
|
||||
Err(Error::new(ENOTDIR))
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the current working directory
|
||||
pub fn getcwd(buf: &mut [u8]) -> Result<usize> {
|
||||
let contexts = context::contexts();
|
||||
let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
|
||||
let context = context_lock.read();
|
||||
let cwd = context.cwd.lock();
|
||||
let mut i = 0;
|
||||
while i < buf.len() && i < cwd.len() {
|
||||
buf[i] = cwd[i];
|
||||
i += 1;
|
||||
}
|
||||
Ok(i)
|
||||
}
|
||||
|
||||
/// Open syscall
|
||||
pub fn open(path: &[u8], flags: usize) -> Result<FileHandle> {
|
||||
let (path_canon, uid, gid, scheme_ns) = {
|
||||
let contexts = context::contexts();
|
||||
let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
|
||||
let context = context_lock.read();
|
||||
(context.canonicalize(path), context.euid, context.egid, context.ens)
|
||||
};
|
||||
|
||||
//println!("open {}", unsafe { ::core::str::from_utf8_unchecked(&path_canon) });
|
||||
|
||||
let mut parts = path_canon.splitn(2, |&b| b == b':');
|
||||
let scheme_name_opt = parts.next();
|
||||
let reference_opt = parts.next();
|
||||
|
||||
let (scheme_id, file_id) = {
|
||||
let scheme_name = scheme_name_opt.ok_or(Error::new(ENODEV))?;
|
||||
let (scheme_id, scheme) = {
|
||||
let schemes = scheme::schemes();
|
||||
let (scheme_id, scheme) = schemes.get_name(scheme_ns, scheme_name).ok_or(Error::new(ENODEV))?;
|
||||
(scheme_id, scheme.clone())
|
||||
};
|
||||
let file_id = scheme.open(reference_opt.unwrap_or(b""), flags, uid, gid)?;
|
||||
(scheme_id, file_id)
|
||||
};
|
||||
|
||||
let contexts = context::contexts();
|
||||
let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
|
||||
let context = context_lock.read();
|
||||
context.add_file(::context::file::File {
|
||||
scheme: scheme_id,
|
||||
number: file_id,
|
||||
event: None,
|
||||
}).ok_or(Error::new(EMFILE))
|
||||
}
|
||||
|
||||
pub fn pipe2(fds: &mut [usize], flags: usize) -> Result<usize> {
|
||||
if fds.len() >= 2 {
|
||||
let scheme_id = ::scheme::pipe::PIPE_SCHEME_ID.load(Ordering::SeqCst);
|
||||
let (read_id, write_id) = ::scheme::pipe::pipe(flags);
|
||||
|
||||
let contexts = context::contexts();
|
||||
let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
|
||||
let context = context_lock.read();
|
||||
|
||||
let read_fd = context.add_file(::context::file::File {
|
||||
scheme: scheme_id,
|
||||
number: read_id,
|
||||
event: None,
|
||||
}).ok_or(Error::new(EMFILE))?;
|
||||
|
||||
let write_fd = context.add_file(::context::file::File {
|
||||
scheme: scheme_id,
|
||||
number: write_id,
|
||||
event: None,
|
||||
}).ok_or(Error::new(EMFILE))?;
|
||||
|
||||
fds[0] = read_fd.into();
|
||||
fds[1] = write_fd.into();
|
||||
|
||||
Ok(0)
|
||||
} else {
|
||||
Err(Error::new(EFAULT))
|
||||
}
|
||||
}
|
||||
|
||||
/// chmod syscall
|
||||
pub fn chmod(path: &[u8], mode: u16) -> Result<usize> {
|
||||
let (path_canon, uid, gid, scheme_ns) = {
|
||||
let contexts = context::contexts();
|
||||
let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
|
||||
let context = context_lock.read();
|
||||
(context.canonicalize(path), context.euid, context.egid, context.ens)
|
||||
};
|
||||
|
||||
let mut parts = path_canon.splitn(2, |&b| b == b':');
|
||||
let scheme_name_opt = parts.next();
|
||||
let reference_opt = parts.next();
|
||||
|
||||
let scheme_name = scheme_name_opt.ok_or(Error::new(ENODEV))?;
|
||||
let scheme = {
|
||||
let schemes = scheme::schemes();
|
||||
let (_scheme_id, scheme) = schemes.get_name(scheme_ns, scheme_name).ok_or(Error::new(ENODEV))?;
|
||||
scheme.clone()
|
||||
};
|
||||
scheme.chmod(reference_opt.unwrap_or(b""), mode, uid, gid)
|
||||
}
|
||||
|
||||
/// rmdir syscall
|
||||
pub fn rmdir(path: &[u8]) -> Result<usize> {
|
||||
let (path_canon, uid, gid, scheme_ns) = {
|
||||
let contexts = context::contexts();
|
||||
let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
|
||||
let context = context_lock.read();
|
||||
(context.canonicalize(path), context.euid, context.egid, context.ens)
|
||||
};
|
||||
|
||||
let mut parts = path_canon.splitn(2, |&b| b == b':');
|
||||
let scheme_name_opt = parts.next();
|
||||
let reference_opt = parts.next();
|
||||
|
||||
let scheme_name = scheme_name_opt.ok_or(Error::new(ENODEV))?;
|
||||
let scheme = {
|
||||
let schemes = scheme::schemes();
|
||||
let (_scheme_id, scheme) = schemes.get_name(scheme_ns, scheme_name).ok_or(Error::new(ENODEV))?;
|
||||
scheme.clone()
|
||||
};
|
||||
scheme.rmdir(reference_opt.unwrap_or(b""), uid, gid)
|
||||
}
|
||||
|
||||
/// Unlink syscall
|
||||
pub fn unlink(path: &[u8]) -> Result<usize> {
|
||||
let (path_canon, uid, gid, scheme_ns) = {
|
||||
let contexts = context::contexts();
|
||||
let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
|
||||
let context = context_lock.read();
|
||||
(context.canonicalize(path), context.euid, context.egid, context.ens)
|
||||
};
|
||||
|
||||
let mut parts = path_canon.splitn(2, |&b| b == b':');
|
||||
let scheme_name_opt = parts.next();
|
||||
let reference_opt = parts.next();
|
||||
|
||||
let scheme_name = scheme_name_opt.ok_or(Error::new(ENODEV))?;
|
||||
let scheme = {
|
||||
let schemes = scheme::schemes();
|
||||
let (_scheme_id, scheme) = schemes.get_name(scheme_ns, scheme_name).ok_or(Error::new(ENODEV))?;
|
||||
scheme.clone()
|
||||
};
|
||||
scheme.unlink(reference_opt.unwrap_or(b""), uid, gid)
|
||||
}
|
||||
|
||||
/// Close syscall
|
||||
pub fn close(fd: FileHandle) -> Result<usize> {
|
||||
let file = {
|
||||
let contexts = context::contexts();
|
||||
let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
|
||||
let context = context_lock.read();
|
||||
let file = context.remove_file(fd).ok_or(Error::new(EBADF))?;
|
||||
file
|
||||
};
|
||||
|
||||
if let Some(event_id) = file.event {
|
||||
context::event::unregister(fd, file.scheme, event_id);
|
||||
}
|
||||
|
||||
let scheme = {
|
||||
let schemes = scheme::schemes();
|
||||
let scheme = schemes.get(file.scheme).ok_or(Error::new(EBADF))?;
|
||||
scheme.clone()
|
||||
};
|
||||
scheme.close(file.number)
|
||||
}
|
||||
|
||||
/// Duplicate file descriptor
|
||||
pub fn dup(fd: FileHandle, buf: &[u8]) -> Result<FileHandle> {
|
||||
let file = {
|
||||
let contexts = context::contexts();
|
||||
let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
|
||||
let context = context_lock.read();
|
||||
let file = context.get_file(fd).ok_or(Error::new(EBADF))?;
|
||||
file
|
||||
};
|
||||
|
||||
let new_id = {
|
||||
let scheme = {
|
||||
let schemes = scheme::schemes();
|
||||
let scheme = schemes.get(file.scheme).ok_or(Error::new(EBADF))?;
|
||||
scheme.clone()
|
||||
};
|
||||
scheme.dup(file.number, buf)?
|
||||
};
|
||||
|
||||
let contexts = context::contexts();
|
||||
let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
|
||||
let context = context_lock.read();
|
||||
context.add_file(::context::file::File {
|
||||
scheme: file.scheme,
|
||||
number: new_id,
|
||||
event: None,
|
||||
}).ok_or(Error::new(EMFILE))
|
||||
}
|
||||
|
||||
/// Duplicate file descriptor, replacing another
|
||||
pub fn dup2(fd: FileHandle, new_fd: FileHandle, buf: &[u8]) -> Result<FileHandle> {
|
||||
if fd == new_fd {
|
||||
Ok(new_fd)
|
||||
} else {
|
||||
let _ = close(new_fd)?;
|
||||
|
||||
let file = {
|
||||
let contexts = context::contexts();
|
||||
let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
|
||||
let context = context_lock.read();
|
||||
let file = context.get_file(fd).ok_or(Error::new(EBADF))?;
|
||||
file
|
||||
};
|
||||
|
||||
let new_id = {
|
||||
let scheme = {
|
||||
let schemes = scheme::schemes();
|
||||
let scheme = schemes.get(file.scheme).ok_or(Error::new(EBADF))?;
|
||||
scheme.clone()
|
||||
};
|
||||
scheme.dup(file.number, buf)?
|
||||
};
|
||||
|
||||
let contexts = context::contexts();
|
||||
let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
|
||||
let context = context_lock.read();
|
||||
context.insert_file(new_fd, ::context::file::File {
|
||||
scheme: file.scheme,
|
||||
number: new_id,
|
||||
event: None,
|
||||
}).ok_or(Error::new(EBADF))
|
||||
}
|
||||
}
|
||||
|
||||
/// Register events for file
|
||||
pub fn fevent(fd: FileHandle, flags: usize) -> Result<usize> {
|
||||
let file = {
|
||||
let contexts = context::contexts();
|
||||
let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
|
||||
let context = context_lock.read();
|
||||
let mut files = context.files.lock();
|
||||
let mut file = files.get_mut(fd.into()).ok_or(Error::new(EBADF))?.ok_or(Error::new(EBADF))?;
|
||||
if let Some(event_id) = file.event.take() {
|
||||
println!("{:?}: {:?}:{}: events already registered: {}", fd, file.scheme, file.number, event_id);
|
||||
context::event::unregister(fd, file.scheme, event_id);
|
||||
}
|
||||
file.clone()
|
||||
};
|
||||
|
||||
let scheme = {
|
||||
let schemes = scheme::schemes();
|
||||
let scheme = schemes.get(file.scheme).ok_or(Error::new(EBADF))?;
|
||||
scheme.clone()
|
||||
};
|
||||
let event_id = scheme.fevent(file.number, flags)?;
|
||||
{
|
||||
let contexts = context::contexts();
|
||||
let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
|
||||
let context = context_lock.read();
|
||||
let mut files = context.files.lock();
|
||||
let mut file = files.get_mut(fd.into()).ok_or(Error::new(EBADF))?.ok_or(Error::new(EBADF))?;
|
||||
file.event = Some(event_id);
|
||||
}
|
||||
context::event::register(fd, file.scheme, event_id);
|
||||
Ok(0)
|
||||
}
|
||||
|
||||
pub fn funmap(virtual_address: usize) -> Result<usize> {
|
||||
if virtual_address == 0 {
|
||||
Ok(0)
|
||||
} else {
|
||||
let contexts = context::contexts();
|
||||
let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
|
||||
let context = context_lock.read();
|
||||
|
||||
let mut grants = context.grants.lock();
|
||||
|
||||
for i in 0 .. grants.len() {
|
||||
let start = grants[i].start_address().get();
|
||||
let end = start + grants[i].size();
|
||||
if virtual_address >= start && virtual_address < end {
|
||||
grants.remove(i).unmap();
|
||||
|
||||
return Ok(0);
|
||||
}
|
||||
}
|
||||
|
||||
Err(Error::new(EFAULT))
|
||||
}
|
||||
}
|
110
kernel/src/syscall/futex.rs
Normal file
110
kernel/src/syscall/futex.rs
Normal file
|
@ -0,0 +1,110 @@
|
|||
use alloc::arc::Arc;
|
||||
use collections::VecDeque;
|
||||
use core::intrinsics;
|
||||
use spin::{Once, RwLock, RwLockReadGuard, RwLockWriteGuard};
|
||||
|
||||
use context::{self, Context};
|
||||
use syscall::error::{Error, Result, ESRCH, EAGAIN, EINVAL};
|
||||
use syscall::flag::{FUTEX_WAIT, FUTEX_WAKE, FUTEX_REQUEUE};
|
||||
use syscall::validate::validate_slice_mut;
|
||||
|
||||
type FutexList = VecDeque<(usize, Arc<RwLock<Context>>)>;
|
||||
|
||||
/// Fast userspace mutex list
|
||||
static FUTEXES: Once<RwLock<FutexList>> = Once::new();
|
||||
|
||||
/// Initialize futexes, called if needed
|
||||
fn init_futexes() -> RwLock<FutexList> {
|
||||
RwLock::new(VecDeque::new())
|
||||
}
|
||||
|
||||
/// Get the global futexes list, const
|
||||
pub fn futexes() -> RwLockReadGuard<'static, FutexList> {
|
||||
FUTEXES.call_once(init_futexes).read()
|
||||
}
|
||||
|
||||
/// Get the global futexes list, mutable
|
||||
pub fn futexes_mut() -> RwLockWriteGuard<'static, FutexList> {
|
||||
FUTEXES.call_once(init_futexes).write()
|
||||
}
|
||||
|
||||
pub fn futex(addr: &mut i32, op: usize, val: i32, val2: usize, addr2: *mut i32) -> Result<usize> {
|
||||
match op {
|
||||
FUTEX_WAIT => {
|
||||
{
|
||||
let mut futexes = futexes_mut();
|
||||
|
||||
let context_lock = {
|
||||
let contexts = context::contexts();
|
||||
let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
|
||||
context_lock.clone()
|
||||
};
|
||||
|
||||
if unsafe { intrinsics::atomic_load(addr) != val } {
|
||||
return Err(Error::new(EAGAIN));
|
||||
}
|
||||
|
||||
context_lock.write().block();
|
||||
|
||||
futexes.push_back((addr as *mut i32 as usize, context_lock));
|
||||
}
|
||||
|
||||
unsafe { context::switch(); }
|
||||
|
||||
Ok(0)
|
||||
},
|
||||
FUTEX_WAKE => {
|
||||
let mut woken = 0;
|
||||
|
||||
{
|
||||
let mut futexes = futexes_mut();
|
||||
|
||||
let mut i = 0;
|
||||
while i < futexes.len() && (woken as i32) < val {
|
||||
if futexes[i].0 == addr as *mut i32 as usize {
|
||||
if let Some(futex) = futexes.swap_remove_back(i) {
|
||||
futex.1.write().unblock();
|
||||
woken += 1;
|
||||
}
|
||||
} else {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(woken)
|
||||
},
|
||||
FUTEX_REQUEUE => {
|
||||
let addr2_safe = validate_slice_mut(addr2, 1).map(|addr2_safe| &mut addr2_safe[0])?;
|
||||
|
||||
let mut woken = 0;
|
||||
let mut requeued = 0;
|
||||
|
||||
{
|
||||
let mut futexes = futexes_mut();
|
||||
|
||||
let mut i = 0;
|
||||
while i < futexes.len() && (woken as i32) < val {
|
||||
if futexes[i].0 == addr as *mut i32 as usize {
|
||||
if let Some(futex) = futexes.swap_remove_back(i) {
|
||||
futex.1.write().unblock();
|
||||
woken += 1;
|
||||
}
|
||||
} else {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
while i < futexes.len() && requeued < val2 {
|
||||
if futexes[i].0 == addr as *mut i32 as usize {
|
||||
futexes[i].0 = addr2_safe as *mut i32 as usize;
|
||||
requeued += 1;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(woken)
|
||||
},
|
||||
_ => Err(Error::new(EINVAL))
|
||||
}
|
||||
}
|
121
kernel/src/syscall/mod.rs
Normal file
121
kernel/src/syscall/mod.rs
Normal file
|
@ -0,0 +1,121 @@
|
|||
///! Syscall handlers
|
||||
|
||||
extern crate syscall;
|
||||
|
||||
pub use self::syscall::{data, error, flag, number, scheme};
|
||||
|
||||
pub use self::driver::*;
|
||||
pub use self::fs::*;
|
||||
pub use self::futex::futex;
|
||||
pub use self::privilege::*;
|
||||
pub use self::process::*;
|
||||
pub use self::time::*;
|
||||
pub use self::validate::*;
|
||||
|
||||
use self::data::TimeSpec;
|
||||
use self::error::{Error, Result, ENOSYS};
|
||||
use self::number::*;
|
||||
|
||||
use context::ContextId;
|
||||
use scheme::{FileHandle, SchemeNamespace};
|
||||
|
||||
/// Driver syscalls
|
||||
pub mod driver;
|
||||
|
||||
/// Filesystem syscalls
|
||||
pub mod fs;
|
||||
|
||||
/// Fast userspace mutex
|
||||
pub mod futex;
|
||||
|
||||
/// Privilege syscalls
|
||||
pub mod privilege;
|
||||
|
||||
/// Process syscalls
|
||||
pub mod process;
|
||||
|
||||
/// Time syscalls
|
||||
pub mod time;
|
||||
|
||||
/// Validate input
|
||||
pub mod validate;
|
||||
|
||||
#[no_mangle]
|
||||
pub extern fn syscall(a: usize, b: usize, c: usize, d: usize, e: usize, f: usize, stack: usize) -> usize {
|
||||
#[inline(always)]
|
||||
fn inner(a: usize, b: usize, c: usize, d: usize, e: usize, f: usize, stack: usize) -> Result<usize> {
|
||||
match a & SYS_CLASS {
|
||||
SYS_CLASS_FILE => {
|
||||
let fd = FileHandle::from(b);
|
||||
match a & SYS_ARG {
|
||||
SYS_ARG_SLICE => file_op_slice(a, fd, validate_slice(c as *const u8, d)?),
|
||||
SYS_ARG_MSLICE => file_op_mut_slice(a, fd, validate_slice_mut(c as *mut u8, d)?),
|
||||
_ => match a {
|
||||
SYS_CLOSE => close(fd),
|
||||
SYS_DUP => dup(fd, validate_slice(c as *const u8, d)?).map(FileHandle::into),
|
||||
SYS_DUP2 => dup2(fd, FileHandle::from(c), validate_slice(d as *const u8, e)?).map(FileHandle::into),
|
||||
SYS_FEVENT => fevent(fd, c),
|
||||
SYS_FUNMAP => funmap(b),
|
||||
_ => file_op(a, fd, c, d)
|
||||
}
|
||||
}
|
||||
},
|
||||
SYS_CLASS_PATH => match a {
|
||||
SYS_OPEN => open(validate_slice(b as *const u8, c)?, d).map(FileHandle::into),
|
||||
SYS_CHMOD => chmod(validate_slice(b as *const u8, c)?, d as u16),
|
||||
SYS_RMDIR => rmdir(validate_slice(b as *const u8, c)?),
|
||||
SYS_UNLINK => unlink(validate_slice(b as *const u8, c)?),
|
||||
_ => unreachable!()
|
||||
},
|
||||
_ => match a {
|
||||
SYS_YIELD => sched_yield(),
|
||||
SYS_NANOSLEEP => nanosleep(validate_slice(b as *const TimeSpec, 1).map(|req| &req[0])?, validate_slice_mut(c as *mut TimeSpec, 1).ok().map(|rem| &mut rem[0])),
|
||||
SYS_CLOCK_GETTIME => clock_gettime(b, validate_slice_mut(c as *mut TimeSpec, 1).map(|time| &mut time[0])?),
|
||||
SYS_FUTEX => futex(validate_slice_mut(b as *mut i32, 1).map(|uaddr| &mut uaddr[0])?, c, d as i32, e, f as *mut i32),
|
||||
SYS_BRK => brk(b),
|
||||
SYS_GETPID => getpid().map(ContextId::into),
|
||||
SYS_CLONE => clone(b, stack).map(ContextId::into),
|
||||
SYS_EXIT => exit((b & 0xFF) << 8),
|
||||
SYS_KILL => kill(ContextId::from(b), c),
|
||||
SYS_WAITPID => waitpid(ContextId::from(b), c, d).map(ContextId::into),
|
||||
SYS_CHDIR => chdir(validate_slice(b as *const u8, c)?),
|
||||
SYS_EXECVE => exec(validate_slice(b as *const u8, c)?, validate_slice(d as *const [usize; 2], e)?),
|
||||
SYS_IOPL => iopl(b, stack),
|
||||
SYS_GETCWD => getcwd(validate_slice_mut(b as *mut u8, c)?),
|
||||
SYS_GETEGID => getegid(),
|
||||
SYS_GETENS => getens(),
|
||||
SYS_GETEUID => geteuid(),
|
||||
SYS_GETGID => getgid(),
|
||||
SYS_GETNS => getns(),
|
||||
SYS_GETUID => getuid(),
|
||||
SYS_MKNS => mkns(validate_slice(b as *const [usize; 2], c)?),
|
||||
SYS_SETREUID => setreuid(b as u32, c as u32),
|
||||
SYS_SETRENS => setrens(SchemeNamespace::from(b), SchemeNamespace::from(c)),
|
||||
SYS_SETREGID => setregid(b as u32, c as u32),
|
||||
SYS_PIPE2 => pipe2(validate_slice_mut(b as *mut usize, 2)?, c),
|
||||
SYS_PHYSALLOC => physalloc(b),
|
||||
SYS_PHYSFREE => physfree(b, c),
|
||||
SYS_PHYSMAP => physmap(b, c, d),
|
||||
SYS_PHYSUNMAP => physunmap(b),
|
||||
SYS_VIRTTOPHYS => virttophys(b),
|
||||
_ => Err(Error::new(ENOSYS))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let result = inner(a, b, c, d, e, f, stack);
|
||||
|
||||
/*
|
||||
if let Err(ref err) = result {
|
||||
let contexts = ::context::contexts();
|
||||
if let Some(context_lock) = contexts.current() {
|
||||
let context = context_lock.read();
|
||||
print!("{}: {}: ", unsafe { ::core::str::from_utf8_unchecked(&context.name.lock()) }, context.id.into());
|
||||
}
|
||||
|
||||
println!("{:X}, {:X}, {:X}, {:X}: {}", a, b, c, d, err);
|
||||
}
|
||||
*/
|
||||
|
||||
Error::mux(result)
|
||||
}
|
147
kernel/src/syscall/privilege.rs
Normal file
147
kernel/src/syscall/privilege.rs
Normal file
|
@ -0,0 +1,147 @@
|
|||
use collections::Vec;
|
||||
|
||||
use context;
|
||||
use scheme::{self, SchemeNamespace};
|
||||
use syscall::error::*;
|
||||
use syscall::validate::validate_slice;
|
||||
|
||||
pub fn getegid() -> Result<usize> {
|
||||
let contexts = context::contexts();
|
||||
let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
|
||||
let context = context_lock.read();
|
||||
Ok(context.egid as usize)
|
||||
}
|
||||
|
||||
pub fn getens() -> Result<usize> {
|
||||
let contexts = context::contexts();
|
||||
let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
|
||||
let context = context_lock.read();
|
||||
Ok(context.ens.into())
|
||||
}
|
||||
|
||||
pub fn geteuid() -> Result<usize> {
|
||||
let contexts = context::contexts();
|
||||
let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
|
||||
let context = context_lock.read();
|
||||
Ok(context.euid as usize)
|
||||
}
|
||||
|
||||
pub fn getgid() -> Result<usize> {
|
||||
let contexts = context::contexts();
|
||||
let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
|
||||
let context = context_lock.read();
|
||||
Ok(context.rgid as usize)
|
||||
}
|
||||
|
||||
pub fn getns() -> Result<usize> {
|
||||
let contexts = context::contexts();
|
||||
let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
|
||||
let context = context_lock.read();
|
||||
Ok(context.rns.into())
|
||||
}
|
||||
|
||||
pub fn getuid() -> Result<usize> {
|
||||
let contexts = context::contexts();
|
||||
let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
|
||||
let context = context_lock.read();
|
||||
Ok(context.ruid as usize)
|
||||
}
|
||||
|
||||
pub fn mkns(name_ptrs: &[[usize; 2]]) -> Result<usize> {
|
||||
let mut names = Vec::new();
|
||||
for name_ptr in name_ptrs {
|
||||
names.push(validate_slice(name_ptr[0] as *const u8, name_ptr[1])?);
|
||||
}
|
||||
|
||||
let (uid, from) = {
|
||||
let contexts = context::contexts();
|
||||
let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
|
||||
let context = context_lock.read();
|
||||
(context.euid, context.ens)
|
||||
};
|
||||
|
||||
if uid == 0 {
|
||||
let to = scheme::schemes_mut().make_ns(from, &names)?;
|
||||
Ok(to.into())
|
||||
} else {
|
||||
Err(Error::new(EACCES))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn setregid(rgid: u32, egid: u32) -> Result<usize> {
|
||||
let contexts = context::contexts();
|
||||
let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
|
||||
let mut context = context_lock.write();
|
||||
|
||||
if (context.euid == 0
|
||||
|| rgid as i32 == -1
|
||||
|| rgid == context.egid
|
||||
|| rgid == context.rgid)
|
||||
&& (context.euid == 0
|
||||
|| egid as i32 == -1
|
||||
|| egid == context.egid
|
||||
|| egid == context.rgid)
|
||||
{
|
||||
if rgid as i32 != -1 {
|
||||
context.rgid = rgid;
|
||||
}
|
||||
if egid as i32 != -1 {
|
||||
context.egid = egid;
|
||||
}
|
||||
Ok(0)
|
||||
} else {
|
||||
Err(Error::new(EPERM))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn setrens(rns: SchemeNamespace, ens: SchemeNamespace) -> Result<usize> {
|
||||
let contexts = context::contexts();
|
||||
let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
|
||||
let mut context = context_lock.write();
|
||||
|
||||
if (context.euid == 0
|
||||
|| rns.into() as isize == -1
|
||||
|| rns == context.ens
|
||||
|| rns == context.rns)
|
||||
&& (context.euid == 0
|
||||
|| ens.into() as isize == -1
|
||||
|| ens == context.ens
|
||||
|| ens == context.rns)
|
||||
{
|
||||
if rns.into() as isize != -1 {
|
||||
context.rns = rns;
|
||||
}
|
||||
if ens.into() as isize != -1 {
|
||||
context.ens = ens;
|
||||
}
|
||||
Ok(0)
|
||||
} else {
|
||||
Err(Error::new(EPERM))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn setreuid(ruid: u32, euid: u32) -> Result<usize> {
|
||||
let contexts = context::contexts();
|
||||
let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
|
||||
let mut context = context_lock.write();
|
||||
|
||||
if (context.euid == 0
|
||||
|| ruid as i32 == -1
|
||||
|| ruid == context.euid
|
||||
|| ruid == context.ruid)
|
||||
&& (context.euid == 0
|
||||
|| euid as i32 == -1
|
||||
|| euid == context.euid
|
||||
|| euid == context.ruid)
|
||||
{
|
||||
if ruid as i32 != -1 {
|
||||
context.ruid = ruid;
|
||||
}
|
||||
if euid as i32 != -1 {
|
||||
context.euid = euid;
|
||||
}
|
||||
Ok(0)
|
||||
} else {
|
||||
Err(Error::new(EPERM))
|
||||
}
|
||||
}
|
965
kernel/src/syscall/process.rs
Normal file
965
kernel/src/syscall/process.rs
Normal file
|
@ -0,0 +1,965 @@
|
|||
///! Process syscalls
|
||||
use alloc::arc::Arc;
|
||||
use alloc::boxed::Box;
|
||||
use collections::{BTreeMap, Vec};
|
||||
use core::{intrinsics, mem, str};
|
||||
use core::ops::DerefMut;
|
||||
use spin::Mutex;
|
||||
|
||||
use arch;
|
||||
use arch::memory::allocate_frame;
|
||||
use arch::paging::{ActivePageTable, InactivePageTable, Page, VirtualAddress, entry};
|
||||
use arch::paging::temporary_page::TemporaryPage;
|
||||
use arch::start::usermode;
|
||||
use context;
|
||||
use context::ContextId;
|
||||
use elf::{self, program_header};
|
||||
use scheme::{self, FileHandle};
|
||||
use syscall;
|
||||
use syscall::data::Stat;
|
||||
use syscall::error::*;
|
||||
use syscall::flag::{CLONE_VFORK, CLONE_VM, CLONE_FS, CLONE_FILES, WNOHANG};
|
||||
use syscall::validate::{validate_slice, validate_slice_mut};
|
||||
|
||||
pub fn brk(address: usize) -> Result<usize> {
|
||||
let contexts = context::contexts();
|
||||
let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
|
||||
let context = context_lock.read();
|
||||
|
||||
//println!("{}: {}: BRK {:X}", unsafe { ::core::str::from_utf8_unchecked(&context.name.lock()) },
|
||||
// context.id.into(), address);
|
||||
|
||||
let current = if let Some(ref heap_shared) = context.heap {
|
||||
heap_shared.with(|heap| {
|
||||
heap.start_address().get() + heap.size()
|
||||
})
|
||||
} else {
|
||||
panic!("user heap not initialized");
|
||||
};
|
||||
|
||||
if address == 0 {
|
||||
//println!("Brk query {:X}", current);
|
||||
Ok(current)
|
||||
} else if address >= arch::USER_HEAP_OFFSET {
|
||||
//TODO: out of memory errors
|
||||
if let Some(ref heap_shared) = context.heap {
|
||||
heap_shared.with(|heap| {
|
||||
heap.resize(address - arch::USER_HEAP_OFFSET, true);
|
||||
});
|
||||
} else {
|
||||
panic!("user heap not initialized");
|
||||
}
|
||||
|
||||
//println!("Brk resize {:X}", address);
|
||||
Ok(address)
|
||||
} else {
|
||||
//println!("Brk no mem");
|
||||
Err(Error::new(ENOMEM))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn clone(flags: usize, stack_base: usize) -> Result<ContextId> {
|
||||
let ppid;
|
||||
let pid;
|
||||
{
|
||||
let ruid;
|
||||
let rgid;
|
||||
let rns;
|
||||
let euid;
|
||||
let egid;
|
||||
let ens;
|
||||
let mut cpu_id = None;
|
||||
let arch;
|
||||
let vfork;
|
||||
let mut kfx_option = None;
|
||||
let mut kstack_option = None;
|
||||
let mut offset = 0;
|
||||
let mut image = vec![];
|
||||
let mut heap_option = None;
|
||||
let mut stack_option = None;
|
||||
let mut tls_option = None;
|
||||
let grants;
|
||||
let name;
|
||||
let cwd;
|
||||
let env;
|
||||
let files;
|
||||
|
||||
// Copy from old process
|
||||
{
|
||||
let contexts = context::contexts();
|
||||
let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
|
||||
let context = context_lock.read();
|
||||
|
||||
ppid = context.id;
|
||||
ruid = context.ruid;
|
||||
rgid = context.rgid;
|
||||
rns = context.rns;
|
||||
euid = context.euid;
|
||||
egid = context.egid;
|
||||
ens = context.ens;
|
||||
|
||||
if flags & CLONE_VM == CLONE_VM {
|
||||
cpu_id = context.cpu_id;
|
||||
}
|
||||
|
||||
arch = context.arch.clone();
|
||||
|
||||
if let Some(ref fx) = context.kfx {
|
||||
let mut new_fx = unsafe { Box::from_raw(::alloc::heap::allocate(512, 16) as *mut [u8; 512]) };
|
||||
for (new_b, b) in new_fx.iter_mut().zip(fx.iter()) {
|
||||
*new_b = *b;
|
||||
}
|
||||
kfx_option = Some(new_fx);
|
||||
}
|
||||
|
||||
if let Some(ref stack) = context.kstack {
|
||||
offset = stack_base - stack.as_ptr() as usize - mem::size_of::<usize>(); // Add clone ret
|
||||
let mut new_stack = stack.clone();
|
||||
|
||||
unsafe {
|
||||
let func_ptr = new_stack.as_mut_ptr().offset(offset as isize);
|
||||
*(func_ptr as *mut usize) = arch::interrupt::syscall::clone_ret as usize;
|
||||
}
|
||||
|
||||
kstack_option = Some(new_stack);
|
||||
}
|
||||
|
||||
if flags & CLONE_VM == CLONE_VM {
|
||||
for memory_shared in context.image.iter() {
|
||||
image.push(memory_shared.clone());
|
||||
}
|
||||
|
||||
if let Some(ref heap_shared) = context.heap {
|
||||
heap_option = Some(heap_shared.clone());
|
||||
}
|
||||
} else {
|
||||
for memory_shared in context.image.iter() {
|
||||
memory_shared.with(|memory| {
|
||||
let mut new_memory = context::memory::Memory::new(
|
||||
VirtualAddress::new(memory.start_address().get() + arch::USER_TMP_OFFSET),
|
||||
memory.size(),
|
||||
entry::PRESENT | entry::NO_EXECUTE | entry::WRITABLE,
|
||||
false
|
||||
);
|
||||
|
||||
unsafe {
|
||||
intrinsics::copy(memory.start_address().get() as *const u8,
|
||||
new_memory.start_address().get() as *mut u8,
|
||||
memory.size());
|
||||
}
|
||||
|
||||
new_memory.remap(memory.flags());
|
||||
image.push(new_memory.to_shared());
|
||||
});
|
||||
}
|
||||
|
||||
if let Some(ref heap_shared) = context.heap {
|
||||
heap_shared.with(|heap| {
|
||||
let mut new_heap = context::memory::Memory::new(
|
||||
VirtualAddress::new(arch::USER_TMP_HEAP_OFFSET),
|
||||
heap.size(),
|
||||
entry::PRESENT | entry::NO_EXECUTE | entry::WRITABLE,
|
||||
false
|
||||
);
|
||||
|
||||
unsafe {
|
||||
intrinsics::copy(heap.start_address().get() as *const u8,
|
||||
new_heap.start_address().get() as *mut u8,
|
||||
heap.size());
|
||||
}
|
||||
|
||||
new_heap.remap(heap.flags());
|
||||
heap_option = Some(new_heap.to_shared());
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(ref stack) = context.stack {
|
||||
let mut new_stack = context::memory::Memory::new(
|
||||
VirtualAddress::new(arch::USER_TMP_STACK_OFFSET),
|
||||
stack.size(),
|
||||
entry::PRESENT | entry::NO_EXECUTE | entry::WRITABLE,
|
||||
false
|
||||
);
|
||||
|
||||
unsafe {
|
||||
intrinsics::copy(stack.start_address().get() as *const u8,
|
||||
new_stack.start_address().get() as *mut u8,
|
||||
stack.size());
|
||||
}
|
||||
|
||||
new_stack.remap(stack.flags());
|
||||
stack_option = Some(new_stack);
|
||||
}
|
||||
|
||||
if let Some(ref tls) = context.tls {
|
||||
let mut new_tls = context::memory::Tls {
|
||||
master: tls.master,
|
||||
file_size: tls.file_size,
|
||||
mem: context::memory::Memory::new(
|
||||
VirtualAddress::new(arch::USER_TMP_TLS_OFFSET),
|
||||
tls.mem.size(),
|
||||
entry::PRESENT | entry::NO_EXECUTE | entry::WRITABLE,
|
||||
true
|
||||
)
|
||||
};
|
||||
|
||||
unsafe {
|
||||
intrinsics::copy(tls.master.get() as *const u8,
|
||||
new_tls.mem.start_address().get() as *mut u8,
|
||||
tls.file_size);
|
||||
}
|
||||
|
||||
new_tls.mem.remap(tls.mem.flags());
|
||||
tls_option = Some(new_tls);
|
||||
}
|
||||
|
||||
if flags & CLONE_VM == CLONE_VM {
|
||||
grants = context.grants.clone();
|
||||
} else {
|
||||
grants = Arc::new(Mutex::new(Vec::new()));
|
||||
}
|
||||
|
||||
if flags & CLONE_VM == CLONE_VM {
|
||||
name = context.name.clone();
|
||||
} else {
|
||||
name = Arc::new(Mutex::new(context.name.lock().clone()));
|
||||
}
|
||||
|
||||
if flags & CLONE_FS == CLONE_FS {
|
||||
cwd = context.cwd.clone();
|
||||
} else {
|
||||
cwd = Arc::new(Mutex::new(context.cwd.lock().clone()));
|
||||
}
|
||||
|
||||
if flags & CLONE_VM == CLONE_VM {
|
||||
env = context.env.clone();
|
||||
} else {
|
||||
let mut new_env = BTreeMap::new();
|
||||
for item in context.env.lock().iter() {
|
||||
new_env.insert(item.0.clone(), Arc::new(Mutex::new(item.1.lock().clone())));
|
||||
}
|
||||
env = Arc::new(Mutex::new(new_env));
|
||||
}
|
||||
|
||||
if flags & CLONE_FILES == CLONE_FILES {
|
||||
files = context.files.clone();
|
||||
} else {
|
||||
files = Arc::new(Mutex::new(context.files.lock().clone()));
|
||||
}
|
||||
}
|
||||
|
||||
// If not cloning files, dup to get a new number from scheme
|
||||
// This has to be done outside the context lock to prevent deadlocks
|
||||
if flags & CLONE_FILES == 0 {
|
||||
for (_fd, mut file_option) in files.lock().iter_mut().enumerate() {
|
||||
let new_file_option = if let Some(file) = *file_option {
|
||||
let result = {
|
||||
let scheme = {
|
||||
let schemes = scheme::schemes();
|
||||
let scheme = schemes.get(file.scheme).ok_or(Error::new(EBADF))?;
|
||||
scheme.clone()
|
||||
};
|
||||
let result = scheme.dup(file.number, b"clone");
|
||||
result
|
||||
};
|
||||
match result {
|
||||
Ok(new_number) => {
|
||||
Some(context::file::File {
|
||||
scheme: file.scheme,
|
||||
number: new_number,
|
||||
event: None,
|
||||
})
|
||||
},
|
||||
Err(_err) => {
|
||||
None
|
||||
}
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
*file_option = new_file_option;
|
||||
}
|
||||
}
|
||||
|
||||
// If vfork, block the current process
|
||||
// This has to be done after the operations that may require context switches
|
||||
if flags & CLONE_VFORK == CLONE_VFORK {
|
||||
let contexts = context::contexts();
|
||||
let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
|
||||
let mut context = context_lock.write();
|
||||
context.block();
|
||||
vfork = true;
|
||||
} else {
|
||||
vfork = false;
|
||||
}
|
||||
|
||||
// Set up new process
|
||||
{
|
||||
let mut contexts = context::contexts_mut();
|
||||
let context_lock = contexts.new_context()?;
|
||||
let mut context = context_lock.write();
|
||||
|
||||
pid = context.id;
|
||||
|
||||
context.ppid = ppid;
|
||||
context.ruid = ruid;
|
||||
context.rgid = rgid;
|
||||
context.rns = rns;
|
||||
context.euid = euid;
|
||||
context.egid = egid;
|
||||
context.ens = ens;
|
||||
|
||||
context.cpu_id = cpu_id;
|
||||
|
||||
context.status = context::Status::Runnable;
|
||||
|
||||
context.vfork = vfork;
|
||||
|
||||
context.arch = arch;
|
||||
|
||||
let mut active_table = unsafe { ActivePageTable::new() };
|
||||
|
||||
let mut temporary_page = TemporaryPage::new(Page::containing_address(VirtualAddress::new(arch::USER_TMP_MISC_OFFSET)));
|
||||
|
||||
let mut new_table = {
|
||||
let frame = allocate_frame().expect("no more frames in syscall::clone new_table");
|
||||
InactivePageTable::new(frame, &mut active_table, &mut temporary_page)
|
||||
};
|
||||
|
||||
context.arch.set_page_table(unsafe { new_table.address() });
|
||||
|
||||
// Copy kernel mapping
|
||||
{
|
||||
let frame = active_table.p4()[510].pointed_frame().expect("kernel table not mapped");
|
||||
let flags = active_table.p4()[510].flags();
|
||||
active_table.with(&mut new_table, &mut temporary_page, |mapper| {
|
||||
mapper.p4_mut()[510].set(frame, flags);
|
||||
});
|
||||
}
|
||||
|
||||
if let Some(fx) = kfx_option.take() {
|
||||
context.arch.set_fx(fx.as_ptr() as usize);
|
||||
context.kfx = Some(fx);
|
||||
}
|
||||
|
||||
// Set kernel stack
|
||||
if let Some(stack) = kstack_option.take() {
|
||||
context.arch.set_stack(stack.as_ptr() as usize + offset);
|
||||
context.kstack = Some(stack);
|
||||
}
|
||||
|
||||
// Setup heap
|
||||
if flags & CLONE_VM == CLONE_VM {
|
||||
// Copy user image mapping, if found
|
||||
if ! image.is_empty() {
|
||||
let frame = active_table.p4()[0].pointed_frame().expect("user image not mapped");
|
||||
let flags = active_table.p4()[0].flags();
|
||||
active_table.with(&mut new_table, &mut temporary_page, |mapper| {
|
||||
mapper.p4_mut()[0].set(frame, flags);
|
||||
});
|
||||
}
|
||||
context.image = image;
|
||||
|
||||
// Copy user heap mapping, if found
|
||||
if let Some(heap_shared) = heap_option {
|
||||
let frame = active_table.p4()[1].pointed_frame().expect("user heap not mapped");
|
||||
let flags = active_table.p4()[1].flags();
|
||||
active_table.with(&mut new_table, &mut temporary_page, |mapper| {
|
||||
mapper.p4_mut()[1].set(frame, flags);
|
||||
});
|
||||
context.heap = Some(heap_shared);
|
||||
}
|
||||
|
||||
// Copy grant mapping
|
||||
if ! grants.lock().is_empty() {
|
||||
let frame = active_table.p4()[2].pointed_frame().expect("user grants not mapped");
|
||||
let flags = active_table.p4()[2].flags();
|
||||
active_table.with(&mut new_table, &mut temporary_page, |mapper| {
|
||||
mapper.p4_mut()[2].set(frame, flags);
|
||||
});
|
||||
}
|
||||
context.grants = grants;
|
||||
} else {
|
||||
// Copy percpu mapping
|
||||
for cpu_id in 0..::cpu_count() {
|
||||
extern {
|
||||
/// The starting byte of the thread data segment
|
||||
static mut __tdata_start: u8;
|
||||
/// The ending byte of the thread BSS segment
|
||||
static mut __tbss_end: u8;
|
||||
}
|
||||
|
||||
let size = unsafe { & __tbss_end as *const _ as usize - & __tdata_start as *const _ as usize };
|
||||
|
||||
let start = arch::KERNEL_PERCPU_OFFSET + arch::KERNEL_PERCPU_SIZE * cpu_id;
|
||||
let end = start + size;
|
||||
|
||||
let start_page = Page::containing_address(VirtualAddress::new(start));
|
||||
let end_page = Page::containing_address(VirtualAddress::new(end - 1));
|
||||
for page in Page::range_inclusive(start_page, end_page) {
|
||||
let frame = active_table.translate_page(page).expect("kernel percpu not mapped");
|
||||
active_table.with(&mut new_table, &mut temporary_page, |mapper| {
|
||||
let result = mapper.map_to(page, frame, entry::PRESENT | entry::NO_EXECUTE | entry::WRITABLE);
|
||||
// Ignore result due to operating on inactive table
|
||||
unsafe { result.ignore(); }
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Move copy of image
|
||||
for memory_shared in image.iter_mut() {
|
||||
memory_shared.with(|memory| {
|
||||
let start = VirtualAddress::new(memory.start_address().get() - arch::USER_TMP_OFFSET + arch::USER_OFFSET);
|
||||
memory.move_to(start, &mut new_table, &mut temporary_page);
|
||||
});
|
||||
}
|
||||
context.image = image;
|
||||
|
||||
// Move copy of heap
|
||||
if let Some(heap_shared) = heap_option {
|
||||
heap_shared.with(|heap| {
|
||||
heap.move_to(VirtualAddress::new(arch::USER_HEAP_OFFSET), &mut new_table, &mut temporary_page);
|
||||
});
|
||||
context.heap = Some(heap_shared);
|
||||
}
|
||||
}
|
||||
|
||||
// Setup user stack
|
||||
if let Some(mut stack) = stack_option {
|
||||
stack.move_to(VirtualAddress::new(arch::USER_STACK_OFFSET), &mut new_table, &mut temporary_page);
|
||||
context.stack = Some(stack);
|
||||
}
|
||||
|
||||
// Setup user TLS
|
||||
if let Some(mut tls) = tls_option {
|
||||
tls.mem.move_to(VirtualAddress::new(arch::USER_TLS_OFFSET), &mut new_table, &mut temporary_page);
|
||||
context.tls = Some(tls);
|
||||
}
|
||||
|
||||
context.name = name;
|
||||
|
||||
context.cwd = cwd;
|
||||
|
||||
context.env = env;
|
||||
|
||||
context.files = files;
|
||||
}
|
||||
}
|
||||
|
||||
unsafe { context::switch(); }
|
||||
|
||||
Ok(pid)
|
||||
}
|
||||
|
||||
fn empty(context: &mut context::Context, reaping: bool) {
|
||||
if reaping {
|
||||
// Memory should already be unmapped
|
||||
assert!(context.image.is_empty());
|
||||
assert!(context.heap.is_none());
|
||||
assert!(context.stack.is_none());
|
||||
assert!(context.tls.is_none());
|
||||
} else {
|
||||
// Unmap previous image, heap, grants, stack, and tls
|
||||
context.image.clear();
|
||||
drop(context.heap.take());
|
||||
drop(context.stack.take());
|
||||
drop(context.tls.take());
|
||||
}
|
||||
|
||||
// FIXME: Looks like a race condition.
|
||||
// Is it possible for Arc::strong_count to return 1 to two contexts that exit at the
|
||||
// same time, or return 2 to both, thus either double freeing or leaking the grants?
|
||||
if Arc::strong_count(&context.grants) == 1 {
|
||||
let mut grants = context.grants.lock();
|
||||
for grant in grants.drain(..) {
|
||||
if reaping {
|
||||
println!("{}: {}: Grant should not exist: {:?}", context.id.into(), unsafe { ::core::str::from_utf8_unchecked(&context.name.lock()) }, grant);
|
||||
|
||||
let mut new_table = unsafe { InactivePageTable::from_address(context.arch.get_page_table()) };
|
||||
let mut temporary_page = TemporaryPage::new(Page::containing_address(VirtualAddress::new(arch::USER_TMP_GRANT_OFFSET)));
|
||||
|
||||
grant.unmap_inactive(&mut new_table, &mut temporary_page);
|
||||
} else {
|
||||
grant.unmap();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn exec(path: &[u8], arg_ptrs: &[[usize; 2]]) -> Result<usize> {
|
||||
let entry;
|
||||
let mut sp = arch::USER_STACK_OFFSET + arch::USER_STACK_SIZE - 256;
|
||||
|
||||
{
|
||||
let mut args = Vec::new();
|
||||
for arg_ptr in arg_ptrs {
|
||||
let arg = validate_slice(arg_ptr[0] as *const u8, arg_ptr[1])?;
|
||||
args.push(arg.to_vec()); // Must be moved into kernel space before exec unmaps all memory
|
||||
}
|
||||
|
||||
let (uid, gid, canonical) = {
|
||||
let contexts = context::contexts();
|
||||
let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
|
||||
let context = context_lock.read();
|
||||
(context.euid, context.egid, context.canonicalize(path))
|
||||
};
|
||||
|
||||
let file = syscall::open(&canonical, syscall::flag::O_RDONLY)?;
|
||||
let mut stat = Stat::default();
|
||||
syscall::file_op_mut_slice(syscall::number::SYS_FSTAT, file, &mut stat)?;
|
||||
|
||||
let mut perm = stat.st_mode & 0o7;
|
||||
if stat.st_uid == uid {
|
||||
perm |= (stat.st_mode >> 6) & 0o7;
|
||||
}
|
||||
if stat.st_gid == gid {
|
||||
perm |= (stat.st_mode >> 3) & 0o7;
|
||||
}
|
||||
if uid == 0 {
|
||||
perm |= 0o7;
|
||||
}
|
||||
|
||||
if perm & 0o1 != 0o1 {
|
||||
let _ = syscall::close(file);
|
||||
return Err(Error::new(EACCES));
|
||||
}
|
||||
|
||||
//TODO: Only read elf header, not entire file. Then read required segments
|
||||
let mut data = vec![0; stat.st_size as usize];
|
||||
syscall::file_op_mut_slice(syscall::number::SYS_READ, file, &mut data)?;
|
||||
let _ = syscall::close(file);
|
||||
|
||||
match elf::Elf::from(&data) {
|
||||
Ok(elf) => {
|
||||
entry = elf.entry();
|
||||
|
||||
drop(path); // 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 (vfork, ppid, files) = {
|
||||
let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
|
||||
let mut context = context_lock.write();
|
||||
|
||||
// Set name
|
||||
context.name = Arc::new(Mutex::new(canonical));
|
||||
|
||||
empty(&mut context, false);
|
||||
|
||||
if stat.st_mode & syscall::flag::MODE_SETUID == syscall::flag::MODE_SETUID {
|
||||
context.euid = stat.st_uid;
|
||||
}
|
||||
|
||||
if stat.st_mode & syscall::flag::MODE_SETGID == syscall::flag::MODE_SETGID {
|
||||
context.egid = stat.st_gid;
|
||||
}
|
||||
|
||||
// Map and copy new segments
|
||||
let mut tls_option = None;
|
||||
for segment in elf.segments() {
|
||||
if segment.p_type == program_header::PT_LOAD {
|
||||
let mut memory = context::memory::Memory::new(
|
||||
VirtualAddress::new(segment.p_vaddr as usize),
|
||||
segment.p_memsz as usize,
|
||||
entry::NO_EXECUTE | entry::WRITABLE,
|
||||
true
|
||||
);
|
||||
|
||||
unsafe {
|
||||
// Copy file data
|
||||
intrinsics::copy((elf.data.as_ptr() as usize + segment.p_offset as usize) as *const u8,
|
||||
segment.p_vaddr as *mut u8,
|
||||
segment.p_filesz as usize);
|
||||
}
|
||||
|
||||
let mut flags = entry::NO_EXECUTE | entry::USER_ACCESSIBLE;
|
||||
|
||||
if segment.p_flags & program_header::PF_R == program_header::PF_R {
|
||||
flags.insert(entry::PRESENT);
|
||||
}
|
||||
|
||||
// W ^ X. If it is executable, do not allow it to be writable, even if requested
|
||||
if segment.p_flags & program_header::PF_X == program_header::PF_X {
|
||||
flags.remove(entry::NO_EXECUTE);
|
||||
} else if segment.p_flags & program_header::PF_W == program_header::PF_W {
|
||||
flags.insert(entry::WRITABLE);
|
||||
}
|
||||
|
||||
memory.remap(flags);
|
||||
|
||||
context.image.push(memory.to_shared());
|
||||
} else if segment.p_type == program_header::PT_TLS {
|
||||
let memory = context::memory::Memory::new(
|
||||
VirtualAddress::new(arch::USER_TCB_OFFSET),
|
||||
4096,
|
||||
entry::NO_EXECUTE | entry::WRITABLE | entry::USER_ACCESSIBLE,
|
||||
true
|
||||
);
|
||||
|
||||
unsafe { *(arch::USER_TCB_OFFSET as *mut usize) = arch::USER_TLS_OFFSET + segment.p_memsz as usize; }
|
||||
|
||||
context.image.push(memory.to_shared());
|
||||
|
||||
tls_option = Some((
|
||||
VirtualAddress::new(segment.p_vaddr as usize),
|
||||
segment.p_filesz as usize,
|
||||
segment.p_memsz as usize
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// Map heap
|
||||
context.heap = Some(context::memory::Memory::new(
|
||||
VirtualAddress::new(arch::USER_HEAP_OFFSET),
|
||||
0,
|
||||
entry::NO_EXECUTE | entry::WRITABLE | entry::USER_ACCESSIBLE,
|
||||
true
|
||||
).to_shared());
|
||||
|
||||
// Map stack
|
||||
context.stack = Some(context::memory::Memory::new(
|
||||
VirtualAddress::new(arch::USER_STACK_OFFSET),
|
||||
arch::USER_STACK_SIZE,
|
||||
entry::NO_EXECUTE | entry::WRITABLE | entry::USER_ACCESSIBLE,
|
||||
true
|
||||
));
|
||||
|
||||
// Map TLS
|
||||
if let Some((master, file_size, size)) = tls_option {
|
||||
let tls = context::memory::Tls {
|
||||
master: master,
|
||||
file_size: file_size,
|
||||
mem: context::memory::Memory::new(
|
||||
VirtualAddress::new(arch::USER_TLS_OFFSET),
|
||||
size,
|
||||
entry::NO_EXECUTE | entry::WRITABLE | entry::USER_ACCESSIBLE,
|
||||
true
|
||||
)
|
||||
};
|
||||
|
||||
unsafe {
|
||||
// Copy file data
|
||||
intrinsics::copy(master.get() as *const u8,
|
||||
tls.mem.start_address().get() as *mut u8,
|
||||
file_size);
|
||||
}
|
||||
|
||||
context.tls = Some(tls);
|
||||
}
|
||||
|
||||
// Push arguments
|
||||
let mut arg_size = 0;
|
||||
for arg in args.iter().rev() {
|
||||
sp -= mem::size_of::<usize>();
|
||||
unsafe { *(sp as *mut usize) = arch::USER_ARG_OFFSET + arg_size; }
|
||||
sp -= mem::size_of::<usize>();
|
||||
unsafe { *(sp as *mut usize) = arg.len(); }
|
||||
|
||||
arg_size += arg.len();
|
||||
}
|
||||
|
||||
sp -= mem::size_of::<usize>();
|
||||
unsafe { *(sp as *mut usize) = args.len(); }
|
||||
|
||||
if arg_size > 0 {
|
||||
let mut memory = context::memory::Memory::new(
|
||||
VirtualAddress::new(arch::USER_ARG_OFFSET),
|
||||
arg_size,
|
||||
entry::NO_EXECUTE | entry::WRITABLE,
|
||||
true
|
||||
);
|
||||
|
||||
let mut arg_offset = 0;
|
||||
for arg in args.iter().rev() {
|
||||
unsafe {
|
||||
intrinsics::copy(arg.as_ptr(),
|
||||
(arch::USER_ARG_OFFSET + arg_offset) as *mut u8,
|
||||
arg.len());
|
||||
}
|
||||
|
||||
arg_offset += arg.len();
|
||||
}
|
||||
|
||||
memory.remap(entry::NO_EXECUTE | entry::USER_ACCESSIBLE);
|
||||
|
||||
context.image.push(memory.to_shared());
|
||||
}
|
||||
|
||||
let files = Arc::new(Mutex::new(context.files.lock().clone()));
|
||||
context.files = files.clone();
|
||||
|
||||
let vfork = context.vfork;
|
||||
context.vfork = false;
|
||||
(vfork, context.ppid, files)
|
||||
};
|
||||
|
||||
// Duplicate current files using b"exec", close previous
|
||||
for (fd, mut file_option) in files.lock().iter_mut().enumerate() {
|
||||
let new_file_option = if let Some(file) = *file_option {
|
||||
// Duplicate
|
||||
let result = {
|
||||
let scheme_option = {
|
||||
let schemes = scheme::schemes();
|
||||
schemes.get(file.scheme).map(|scheme| scheme.clone())
|
||||
};
|
||||
if let Some(scheme) = scheme_option {
|
||||
let result = scheme.dup(file.number, b"exec");
|
||||
result
|
||||
} else {
|
||||
Err(Error::new(EBADF))
|
||||
}
|
||||
};
|
||||
|
||||
// Close
|
||||
{
|
||||
if let Some(event_id) = file.event {
|
||||
context::event::unregister(FileHandle::from(fd), file.scheme, event_id);
|
||||
}
|
||||
|
||||
let scheme_option = {
|
||||
let schemes = scheme::schemes();
|
||||
schemes.get(file.scheme).map(|scheme| scheme.clone())
|
||||
};
|
||||
if let Some(scheme) = scheme_option {
|
||||
let _ = scheme.close(file.number);
|
||||
}
|
||||
}
|
||||
|
||||
// Return new descriptor
|
||||
match result {
|
||||
Ok(new_number) => {
|
||||
Some(context::file::File {
|
||||
scheme: file.scheme,
|
||||
number: new_number,
|
||||
event: None,
|
||||
})
|
||||
},
|
||||
Err(_err) => {
|
||||
None
|
||||
}
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
*file_option = new_file_option;
|
||||
}
|
||||
|
||||
if vfork {
|
||||
if let Some(context_lock) = contexts.get(ppid) {
|
||||
let mut context = context_lock.write();
|
||||
if ! context.unblock() {
|
||||
println!("{:?} not blocked for exec vfork unblock", ppid);
|
||||
}
|
||||
} else {
|
||||
println!("{:?} not found for exec vfork unblock", ppid);
|
||||
}
|
||||
}
|
||||
},
|
||||
Err(err) => {
|
||||
println!("failed to execute {}: {}", unsafe { str::from_utf8_unchecked(path) }, err);
|
||||
return Err(Error::new(ENOEXEC));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Go to usermode
|
||||
unsafe { usermode(entry, sp); }
|
||||
}
|
||||
|
||||
pub fn exit(status: usize) -> ! {
|
||||
{
|
||||
let context_lock = {
|
||||
let contexts = context::contexts();
|
||||
let context_lock = contexts.current().ok_or(Error::new(ESRCH)).expect("exit failed to find context");
|
||||
context_lock.clone()
|
||||
};
|
||||
|
||||
let mut close_files = Vec::new();
|
||||
let (pid, ppid) = {
|
||||
let mut context = context_lock.write();
|
||||
// FIXME: Looks like a race condition.
|
||||
// Is it possible for Arc::strong_count to return 1 to two contexts that exit at the
|
||||
// same time, or return 2 to both, thus either double closing or leaking the files?
|
||||
if Arc::strong_count(&context.files) == 1 {
|
||||
mem::swap(context.files.lock().deref_mut(), &mut close_files);
|
||||
}
|
||||
context.files = Arc::new(Mutex::new(Vec::new()));
|
||||
(context.id, context.ppid)
|
||||
};
|
||||
|
||||
/// Files must be closed while context is valid so that messages can be passed
|
||||
for (fd, file_option) in close_files.drain(..).enumerate() {
|
||||
if let Some(file) = file_option {
|
||||
if let Some(event_id) = file.event {
|
||||
context::event::unregister(FileHandle::from(fd), file.scheme, event_id);
|
||||
}
|
||||
|
||||
let scheme_option = {
|
||||
let schemes = scheme::schemes();
|
||||
schemes.get(file.scheme).map(|scheme| scheme.clone())
|
||||
};
|
||||
if let Some(scheme) = scheme_option {
|
||||
let _ = scheme.close(file.number);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Transfer child processes to parent
|
||||
{
|
||||
let contexts = context::contexts();
|
||||
for (_id, context_lock) in contexts.iter() {
|
||||
let mut context = context_lock.write();
|
||||
if context.ppid == pid {
|
||||
context.ppid = ppid;
|
||||
context.vfork = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let (vfork, children) = {
|
||||
let mut context = context_lock.write();
|
||||
|
||||
empty(&mut context, false);
|
||||
|
||||
let vfork = context.vfork;
|
||||
context.vfork = false;
|
||||
|
||||
context.status = context::Status::Exited(status);
|
||||
|
||||
let children = context.waitpid.receive_all();
|
||||
|
||||
(vfork, children)
|
||||
};
|
||||
|
||||
{
|
||||
let contexts = context::contexts();
|
||||
if let Some(parent_lock) = contexts.get(ppid) {
|
||||
let waitpid = {
|
||||
let mut parent = parent_lock.write();
|
||||
if vfork {
|
||||
if ! parent.unblock() {
|
||||
println!("{:?} not blocked for exit vfork unblock", ppid);
|
||||
}
|
||||
}
|
||||
parent.waitpid.clone()
|
||||
};
|
||||
|
||||
for (c_pid, c_status) in children {
|
||||
waitpid.send(c_pid, c_status);
|
||||
}
|
||||
waitpid.send(pid, status);
|
||||
} else {
|
||||
println!("{:?} not found for exit vfork unblock", ppid);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
unsafe { context::switch(); }
|
||||
|
||||
unreachable!();
|
||||
}
|
||||
|
||||
pub fn getpid() -> Result<ContextId> {
|
||||
let contexts = context::contexts();
|
||||
let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
|
||||
let context = context_lock.read();
|
||||
Ok(context.id)
|
||||
}
|
||||
|
||||
pub fn kill(pid: ContextId, sig: usize) -> Result<usize> {
|
||||
let (ruid, euid) = {
|
||||
let contexts = context::contexts();
|
||||
let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
|
||||
let context = context_lock.read();
|
||||
(context.ruid, context.euid)
|
||||
};
|
||||
|
||||
if sig > 0 && sig <= 0x7F {
|
||||
let contexts = context::contexts();
|
||||
let context_lock = contexts.get(pid).ok_or(Error::new(ESRCH))?;
|
||||
let mut context = context_lock.write();
|
||||
if euid == 0
|
||||
|| euid == context.ruid
|
||||
|| ruid == context.ruid
|
||||
{
|
||||
context.pending.push_back(sig as u8);
|
||||
Ok(0)
|
||||
} else {
|
||||
Err(Error::new(EPERM))
|
||||
}
|
||||
} else {
|
||||
Err(Error::new(EINVAL))
|
||||
}
|
||||
}
|
||||
|
||||
fn reap(pid: ContextId) -> Result<ContextId> {
|
||||
// Spin until not running
|
||||
let mut running = false;
|
||||
while running {
|
||||
{
|
||||
let contexts = context::contexts();
|
||||
let context_lock = contexts.get(pid).ok_or(Error::new(ESRCH))?;
|
||||
let context = context_lock.read();
|
||||
running = context.running;
|
||||
}
|
||||
|
||||
arch::interrupt::pause();
|
||||
}
|
||||
|
||||
let mut contexts = context::contexts_mut();
|
||||
let context_lock = contexts.remove(pid).ok_or(Error::new(ESRCH))?;
|
||||
{
|
||||
let mut context = context_lock.write();
|
||||
empty(&mut context, true);
|
||||
}
|
||||
drop(context_lock);
|
||||
|
||||
Ok(pid)
|
||||
}
|
||||
|
||||
pub fn waitpid(pid: ContextId, status_ptr: usize, flags: usize) -> Result<ContextId> {
|
||||
let waitpid = {
|
||||
let contexts = context::contexts();
|
||||
let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
|
||||
let context = context_lock.read();
|
||||
context.waitpid.clone()
|
||||
};
|
||||
|
||||
let mut tmp = [0];
|
||||
let status_slice = if status_ptr != 0 {
|
||||
validate_slice_mut(status_ptr as *mut usize, 1)?
|
||||
} else {
|
||||
&mut tmp
|
||||
};
|
||||
|
||||
if pid.into() == 0 {
|
||||
if flags & WNOHANG == WNOHANG {
|
||||
if let Some((w_pid, status)) = waitpid.receive_any_nonblock() {
|
||||
status_slice[0] = status;
|
||||
reap(w_pid)
|
||||
} else {
|
||||
Ok(ContextId::from(0))
|
||||
}
|
||||
} else {
|
||||
let (w_pid, status) = waitpid.receive_any();
|
||||
status_slice[0] = status;
|
||||
reap(w_pid)
|
||||
}
|
||||
} else {
|
||||
if flags & WNOHANG == WNOHANG {
|
||||
if let Some(status) = waitpid.receive_nonblock(&pid) {
|
||||
status_slice[0] = status;
|
||||
reap(pid)
|
||||
} else {
|
||||
Ok(ContextId::from(0))
|
||||
}
|
||||
} else {
|
||||
let status = waitpid.receive(&pid);
|
||||
status_slice[0] = status;
|
||||
reap(pid)
|
||||
}
|
||||
}
|
||||
}
|
53
kernel/src/syscall/time.rs
Normal file
53
kernel/src/syscall/time.rs
Normal file
|
@ -0,0 +1,53 @@
|
|||
use arch;
|
||||
use context;
|
||||
use syscall::data::TimeSpec;
|
||||
use syscall::error::*;
|
||||
use syscall::flag::{CLOCK_REALTIME, CLOCK_MONOTONIC};
|
||||
|
||||
pub fn clock_gettime(clock: usize, time: &mut TimeSpec) -> Result<usize> {
|
||||
match clock {
|
||||
CLOCK_REALTIME => {
|
||||
let arch_time = arch::time::realtime();
|
||||
time.tv_sec = arch_time.0 as i64;
|
||||
time.tv_nsec = arch_time.1 as i32;
|
||||
Ok(0)
|
||||
},
|
||||
CLOCK_MONOTONIC => {
|
||||
let arch_time = arch::time::monotonic();
|
||||
time.tv_sec = arch_time.0 as i64;
|
||||
time.tv_nsec = arch_time.1 as i32;
|
||||
Ok(0)
|
||||
},
|
||||
_ => Err(Error::new(EINVAL))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn nanosleep(req: &TimeSpec, rem_opt: Option<&mut TimeSpec>) -> Result<usize> {
|
||||
let start = arch::time::monotonic();
|
||||
let sum = start.1 + req.tv_nsec as u64;
|
||||
let end = (start.0 + req.tv_sec as u64 + sum / 1000000000, sum % 1000000000);
|
||||
|
||||
{
|
||||
let contexts = context::contexts();
|
||||
let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;
|
||||
let mut context = context_lock.write();
|
||||
|
||||
context.wake = Some(end);
|
||||
context.block();
|
||||
}
|
||||
|
||||
unsafe { context::switch(); }
|
||||
|
||||
if let Some(mut rem) = rem_opt {
|
||||
//TODO let current = arch::time::monotonic();
|
||||
rem.tv_sec = 0;
|
||||
rem.tv_nsec = 0;
|
||||
}
|
||||
|
||||
Ok(0)
|
||||
}
|
||||
|
||||
pub fn sched_yield() -> Result<usize> {
|
||||
unsafe { context::switch(); }
|
||||
Ok(0)
|
||||
}
|
44
kernel/src/syscall/validate.rs
Normal file
44
kernel/src/syscall/validate.rs
Normal file
|
@ -0,0 +1,44 @@
|
|||
use core::{mem, slice};
|
||||
|
||||
use arch::paging::{ActivePageTable, Page, VirtualAddress, entry};
|
||||
use syscall::error::*;
|
||||
|
||||
fn validate(address: usize, size: usize, flags: entry::EntryFlags) -> Result<()> {
|
||||
let active_table = unsafe { ActivePageTable::new() };
|
||||
|
||||
let start_page = Page::containing_address(VirtualAddress::new(address));
|
||||
let end_page = Page::containing_address(VirtualAddress::new(address + size - 1));
|
||||
for page in Page::range_inclusive(start_page, end_page) {
|
||||
if let Some(page_flags) = active_table.translate_page_flags(page) {
|
||||
if ! page_flags.contains(flags) {
|
||||
//println!("{:X}: Not {:?}", page.start_address().get(), flags);
|
||||
return Err(Error::new(EFAULT));
|
||||
}
|
||||
} else {
|
||||
//println!("{:X}: Not found", page.start_address().get());
|
||||
return Err(Error::new(EFAULT));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Convert a pointer and length to slice, if valid
|
||||
pub fn validate_slice<T>(ptr: *const T, len: usize) -> Result<&'static [T]> {
|
||||
if len == 0 {
|
||||
Ok(&[])
|
||||
} else {
|
||||
validate(ptr as usize, len * mem::size_of::<T>(), entry::PRESENT /* TODO | entry::USER_ACCESSIBLE */)?;
|
||||
Ok(unsafe { slice::from_raw_parts(ptr, len) })
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert a pointer and length to slice, if valid
|
||||
pub fn validate_slice_mut<T>(ptr: *mut T, len: usize) -> Result<&'static mut [T]> {
|
||||
if len == 0 {
|
||||
Ok(&mut [])
|
||||
} else {
|
||||
validate(ptr as usize, len * mem::size_of::<T>(), entry::PRESENT | entry::WRITABLE /* TODO | entry::USER_ACCESSIBLE */)?;
|
||||
Ok(unsafe { slice::from_raw_parts_mut(ptr, len) })
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue