Skip to content

Commit

Permalink
Make clone unsafe
Browse files Browse the repository at this point in the history
There are many features of `clone` that may cause memory unsafety when
called. This documents one of them and references `fork()`, which is
already unsafe to call.
  • Loading branch information
djkoloski committed Jan 31, 2023
1 parent 1a838c7 commit 01035ee
Showing 1 changed file with 23 additions and 15 deletions.
38 changes: 23 additions & 15 deletions src/sched.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,17 @@ mod sched_linux_like {
/// address need not be the highest address of the region. Nix will take
/// care of that requirement. The user only needs to provide a reference to
/// a normally allocated buffer.
pub fn clone(
///
/// # Safety
///
/// Because `clone` creates a child process with its stack located in
/// `stack` without specifying the size of the stack, special care must be
/// taken to ensure that the child process does not overflow the provided
/// stack space.
///
/// See [`fork`](crate::unistd::fork) for additional safety concerns related
/// to executing child processes.
pub unsafe fn clone(
mut cb: CloneCb,
stack: &mut [u8],
flags: CloneFlags,
Expand All @@ -106,20 +116,18 @@ mod sched_linux_like {
(*cb)() as c_int
}

let res = unsafe {
let combined = flags.bits() | signal.unwrap_or(0);
let ptr = stack.as_mut_ptr().add(stack.len());
let ptr_aligned = ptr.sub(ptr as usize % 16);
libc::clone(
mem::transmute(
callback
as extern "C" fn(*mut Box<dyn FnMut() -> isize>) -> i32,
),
ptr_aligned as *mut c_void,
combined,
&mut cb as *mut _ as *mut c_void,
)
};
let combined = flags.bits() | signal.unwrap_or(0);
let ptr = stack.as_mut_ptr().add(stack.len());
let ptr_aligned = ptr.sub(ptr as usize % 16);
let res = libc::clone(
mem::transmute(
callback
as extern "C" fn(*mut Box<dyn FnMut() -> isize>) -> i32,
),
ptr_aligned as *mut c_void,
combined,
&mut cb as *mut _ as *mut c_void,
);

Errno::result(res).map(Pid::from_raw)
}
Expand Down

0 comments on commit 01035ee

Please sign in to comment.