1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
use std::fs;
use std::io;
use std::path::Path;
use std::process;
use std::result;
use errno_result;
use libc::{c_long, pid_t, syscall, CLONE_NEWPID, CLONE_NEWUSER, SIGCHLD};
use syscall_defines::linux::LinuxSyscall::SYS_clone;
#[repr(u32)]
pub enum CloneNamespace {
Inherit = 0,
NewUserPid = CLONE_NEWUSER as u32 | CLONE_NEWPID as u32,
}
#[derive(Debug)]
pub enum CloneError {
IterateTasks(io::Error),
Multithreaded(usize),
Sys(::Error),
}
unsafe fn do_clone(flags: i32) -> ::Result<pid_t> {
let pid = syscall(SYS_clone as c_long, flags | SIGCHLD as i32, 0);
if pid < 0 {
errno_result()
} else {
Ok(pid as pid_t)
}
}
fn count_dir_entries<P: AsRef<Path>>(path: P) -> io::Result<usize> {
Ok(fs::read_dir(path)?.count())
}
pub fn clone_process<F>(ns: CloneNamespace, post_clone_cb: F) -> result::Result<pid_t, CloneError>
where
F: FnOnce(),
{
match count_dir_entries("/proc/self/task") {
Ok(1) => {}
Ok(thread_count) => {
let _ = thread_count;
#[cfg(not(test))]
return Err(CloneError::Multithreaded(thread_count));
}
Err(e) => return Err(CloneError::IterateTasks(e)),
}
let ret = unsafe { do_clone(ns as i32) }.map_err(CloneError::Sys)?;
if ret == 0 {
struct ExitGuard;
impl Drop for ExitGuard {
fn drop(&mut self) {
process::exit(101);
}
}
#[allow(unused_variables)]
let exit_guard = ExitGuard {};
post_clone_cb();
process::exit(0);
}
Ok(ret)
}
#[cfg(test)]
mod tests {
use super::*;
use libc;
use {getpid, EventFd};
fn wait_process(pid: libc::pid_t) -> ::Result<libc::c_int> {
let mut status: libc::c_int = 0;
unsafe {
if libc::waitpid(pid, &mut status as *mut libc::c_int, 0) < 0 {
errno_result()
} else {
Ok(libc::WEXITSTATUS(status))
}
}
}
#[test]
fn pid_diff() {
let evt_fd = EventFd::new().expect("failed to create EventFd");
let evt_fd_fork = evt_fd.try_clone().expect("failed to clone EventFd");
let pid = getpid();
clone_process(CloneNamespace::Inherit, || {
if pid != getpid() {
evt_fd_fork.write(1).unwrap()
} else {
evt_fd_fork.write(2).unwrap()
}
})
.expect("failed to clone");
assert_eq!(evt_fd.read(), Ok(1));
}
#[test]
fn panic_safe() {
let pid = getpid();
assert_ne!(pid, 0);
let clone_pid = clone_process(CloneNamespace::Inherit, || {
assert!(false);
})
.expect("failed to clone");
if pid != getpid() {
process::exit(2);
}
let status = wait_process(clone_pid).expect("wait_process failed");
assert!(status == 101 || status == 0);
}
}