Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

rt_sigprocmask syscall implementation #112

Merged
merged 8 commits into from
Dec 7, 2021
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 50 additions & 14 deletions kernel/process/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,13 @@ use crate::{
elf::{Elf, ProgramHeader},
init_stack::{estimate_user_init_stack_size, init_user_stack, Auxv},
process_group::{PgId, ProcessGroup},
signal::{SigAction, Signal, SignalDelivery, SIGCHLD, SIGKILL},
signal::{SigAction, Signal, SignalDelivery, SignalMask, SIGCHLD, SIGKILL},
switch, UserVAddr, JOIN_WAIT_QUEUE, SCHEDULER,
},
random::read_secure_random,
result::Errno,
INITIAL_ROOT_FS,
};

use alloc::collections::BTreeMap;
use alloc::sync::{Arc, Weak};
use alloc::vec::Vec;
Expand All @@ -36,7 +36,9 @@ use kerla_runtime::{
page_allocator::{alloc_pages, AllocPageFlags},
spinlock::{SpinLock, SpinLockGuard},
};
use kerla_utils::alignment::align_up;
use kerla_utils::{alignment::align_up, bitmap::BitMap};

use super::signal::SigSet;

type ProcessTable = BTreeMap<PId, Arc<Process>>;

Expand Down Expand Up @@ -104,6 +106,7 @@ pub struct Process {
root_fs: Arc<SpinLock<RootFs>>,
signals: SpinLock<SignalDelivery>,
signaled_frame: AtomicCell<Option<PtRegs>>,
sigset: SpinLock<SigSet>,
}

impl Process {
Expand All @@ -126,6 +129,7 @@ impl Process {
opened_files: SpinLock::new(OpenedFileTable::new()),
signals: SpinLock::new(SignalDelivery::new()),
signaled_frame: AtomicCell::new(None),
sigset: SpinLock::new(BitMap::zeroed()),
});

process_group.lock().add(Arc::downgrade(&proc));
Expand Down Expand Up @@ -187,6 +191,7 @@ impl Process {
root_fs,
signals: SpinLock::new(SignalDelivery::new()),
signaled_frame: AtomicCell::new(None),
sigset: SpinLock::new(BitMap::zeroed()),
});

process_group.lock().add(Arc::downgrade(&process));
Expand Down Expand Up @@ -351,6 +356,32 @@ impl Process {
self.signals.lock().is_pending()
}

/// Sets signal mask.
pub fn set_signal_mask(
&self,
how: SignalMask,
set: Option<UserVAddr>,
oldset: Option<UserVAddr>,
_length: usize,
) -> Result<()> {
let mut sigset = self.sigset.lock();

if let Some(old) = oldset {
old.write_bytes(sigset.as_slice())?;
}

if let Some(new) = set {
let new_set = new.read::<[u8; 128]>()?;
match how {
SignalMask::Block => sigset.assign_or(new_set),
SignalMask::Unblock => sigset.assign_and_not(new_set),
SignalMask::Set => sigset.assign(new_set),
}
}

Ok(())
}

/// Tries to delivering a pending signal to the current process.
///
/// If there's a pending signal, it may modify `frame` (e.g. user return
Expand All @@ -359,17 +390,20 @@ impl Process {
// TODO: sigmask
Lurk marked this conversation as resolved.
Show resolved Hide resolved
let current = current_process();
if let Some((signal, sigaction)) = current.signals.lock().pop_pending() {
match sigaction {
SigAction::Ignore => {}
SigAction::Terminate => {
trace!("terminating {:?} by {:?}", current.pid, signal,);
Process::exit(1 /* FIXME: */);
}
SigAction::Handler { handler } => {
trace!("delivering {:?} to {:?}", signal, current.pid,);
current.signaled_frame.store(Some(*frame));
unsafe {
current.arch.setup_signal_stack(frame, signal, handler)?;
let sigset = current.sigset.lock();
if !sigset.get(signal as usize).unwrap_or(true) {
match sigaction {
SigAction::Ignore => {}
SigAction::Terminate => {
trace!("terminating {:?} by {:?}", current.pid, signal,);
Process::exit(1 /* FIXME: */);
}
SigAction::Handler { handler } => {
trace!("delivering {:?} to {:?}", signal, current.pid,);
current.signaled_frame.store(Some(*frame));
unsafe {
current.arch.setup_signal_stack(frame, signal, handler)?;
}
}
}
}
Expand Down Expand Up @@ -433,6 +467,7 @@ impl Process {
let vm = parent.vm().as_ref().unwrap().lock().fork()?;
let opened_files = parent.opened_files().lock().fork();
let process_group = parent.process_group();
let sig_set = parent.sigset.lock();

let child = Arc::new(Process {
process_group: AtomicRefCell::new(Arc::downgrade(&process_group)),
Expand All @@ -447,6 +482,7 @@ impl Process {
arch,
signals: SpinLock::new(SignalDelivery::new()),
signaled_frame: AtomicCell::new(None),
sigset: SpinLock::new(sig_set.clone()),
});

process_group.lock().add(Arc::downgrade(&child));
Expand Down
8 changes: 8 additions & 0 deletions kernel/process/signal.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::{ctypes::c_int, prelude::*};
use kerla_runtime::address::UserVAddr;
use kerla_utils::bitmap::BitMap;

pub type Signal = c_int;
#[allow(unused)]
Expand Down Expand Up @@ -153,3 +154,10 @@ impl SignalDelivery {
self.pending |= 1 << (signal);
}
}

pub type SigSet = BitMap<128 /* 1024 / 8 */>;
pub enum SignalMask {
Block,
Unblock,
Set,
}
5 changes: 5 additions & 0 deletions kernel/syscalls/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ pub(self) mod readlink;
pub(self) mod reboot;
pub(self) mod recvfrom;
pub(self) mod rt_sigaction;
pub(self) mod rt_sigprocmask;
pub(self) mod rt_sigreturn;
pub(self) mod select;
pub(self) mod sendto;
Expand Down Expand Up @@ -112,6 +113,7 @@ const SYS_POLL: usize = 7;
const SYS_MMAP: usize = 9;
const SYS_BRK: usize = 12;
const SYS_RT_SIGACTION: usize = 13;
const SYS_RT_SIGPROCMASK: usize = 14;
const SYS_RT_SIGRETURN: usize = 15;
const SYS_IOCTL: usize = 16;
const SYS_WRITEV: usize = 20;
Expand Down Expand Up @@ -368,6 +370,9 @@ impl<'a> SyscallHandler<'a> {
SYS_SYSLOG => self.sys_syslog(a1 as c_int, UserVAddr::new(a2), a3 as c_int),
SYS_REBOOT => self.sys_reboot(a1 as c_int, a2 as c_int, a3),
SYS_GETTID => self.sys_gettid(),
SYS_RT_SIGPROCMASK => {
self.sys_rt_sigprocmask(a1, UserVAddr::new(a2), UserVAddr::new(a3), a4)
}
_ => {
debug_warn!(
"unimplemented system call: {} (n={})",
Expand Down
29 changes: 29 additions & 0 deletions kernel/syscalls/rt_sigprocmask.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
use crate::prelude::*;
use crate::process::current_process;

use crate::process::signal::SignalMask;
use crate::syscalls::SyscallHandler;
use kerla_runtime::address::UserVAddr;

impl SyscallHandler<'_> {
pub fn sys_rt_sigprocmask(
&mut self,
how: usize,
set: Option<UserVAddr>,
oldset: Option<UserVAddr>,
length: usize,
) -> Result<isize> {
let how = match how {
0 => SignalMask::Block,
1 => SignalMask::Unblock,
2 => SignalMask::Set,
_ => return Err(Errno::EINVAL.into()),
};

if let Err(_) = current_process().set_signal_mask(how, set, oldset, length) {
return Err(Errno::EFAULT.into());
}

Ok(0)
}
}
34 changes: 33 additions & 1 deletion libs/kerla_utils/bitmap.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use core::slice::memchr::memchr;

#[derive(Clone)]
pub struct BitMap<const SZ: usize>([u8; SZ]);

impl<const SZ: usize> BitMap<SZ> {
Expand All @@ -12,7 +13,6 @@ impl<const SZ: usize> BitMap<SZ> {
BitMap(array)
}

#[cfg(test)]
pub fn as_slice(&self) -> &[u8] {
&self.0
}
Expand Down Expand Up @@ -51,6 +51,24 @@ impl<const SZ: usize> BitMap<SZ> {

None
}

pub fn assign(&mut self, rhs: [u8; SZ]) {
self.0 = rhs;
}

/// This method will panic if SZ != rhs.len()
pub fn assign_or(&mut self, rhs: [u8; SZ]) {
for (i, byte) in self.0.iter_mut().enumerate() {
*byte |= rhs[i];
}
}

/// This method will panic if SZ != rhs.len()
pub fn assign_and_not(&mut self, rhs: [u8; SZ]) {
for (i, byte) in self.0.iter_mut().enumerate() {
*byte &= !rhs[i];
}
}
}

#[cfg(all(test, not(feature = "no_std")))]
Expand All @@ -71,4 +89,18 @@ mod tests {
assert_eq!(bitmap.as_slice(), &[0b1111_1111, 0b1111_1001]);
assert_eq!(bitmap.first_zero(), Some(9));
}

#[test]
fn or() {
let mut bitmap = BitMap::from_array([0b0100_0010, 0b1000_0001]);
bitmap.assign_or([0b0010_0100, 0b1010_0110]);
assert_eq!(bitmap.as_slice(), &[0b0110_0110, 0b1010_0111]);
}

#[test]
fn material_nonimplication() {
Lurk marked this conversation as resolved.
Show resolved Hide resolved
let mut bitmap = BitMap::from_array([0b0100_0010, 0b1000_0001]);
bitmap.assign_and_not([0b0110_0100, 0b1010_0110]);
assert_eq!(bitmap.as_slice(), &[0b0000_0010, 0b0000_0001]);
}
}