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::ffi::CString;
use crate::ProcessOutput;
use crate::pipe::Pipe;
use std::rc::Rc;
use crate::error::UECOError;
use crate::libc_util::{libc_ret_to_result, LibcSyscall};
fn exec(executable: &str, args: Vec<&str>) -> Result<(), UECOError> {
let executable = CString::new(executable).expect("Executable must not contain null!");
let executable = executable.as_c_str();
let args = args
.iter()
.map(|s| CString::new(*s).expect("Arg not contain null!"))
.collect::<Vec<CString>>();
let mut args_nl = args.iter()
.map(|cs| cs.as_ptr())
.collect::<Vec<* const i8>>();
args_nl.push(std::ptr::null());
let ret = unsafe { libc::execvp(executable.as_ptr(), args_nl.as_ptr()) };
let res = libc_ret_to_result(ret, LibcSyscall::Execvp);
res
}
pub fn fork_exec_and_catch(executable: &str, args: Vec<&str>) -> Result<ProcessOutput, UECOError> {
trace!("creating stdout pipe:");
let mut stdout_pipe = Pipe::new()?;
trace!("creating stderr pipe:");
let mut stderr_pipe = Pipe::new()?;
let pid = unsafe { libc::fork() };
libc_ret_to_result(pid, LibcSyscall::Fork)?;
trace!("forked successfully");
if pid == 0 {
trace!("Hello from Child!");
stdout_pipe.mark_as_child_process()?;
stderr_pipe.mark_as_child_process()?;
let res = unsafe { libc::dup2(stdout_pipe.write_fd(), libc::STDOUT_FILENO) };
libc_ret_to_result(res, LibcSyscall::Dup2)?;
let res = unsafe { libc::dup2(stderr_pipe.write_fd(), libc::STDERR_FILENO) };
libc_ret_to_result(res, LibcSyscall::Dup2)?;
exec(executable, args)?;
} else {
trace!("Hello from parent!");
stdout_pipe.mark_as_parent_process()?;
stderr_pipe.mark_as_parent_process()?;
let mut stdout_lines = vec![];
let mut stderr_lines = vec![];
let mut stdcombined_lines = vec![];
loop {
let mut stdout_eof = false;
let mut stderr_eof = false;
let stdout_line = stdout_pipe.read_line()?;
let stderr_line = stderr_pipe.read_line()?;
let stdout_line = stdout_line.map(|l| Rc::new(l));
let stderr_line = stderr_line.map(|l| Rc::new(l));
if let Some(l) = stdout_line {
stdout_lines.push(l.clone());
stdcombined_lines.push(l);
} else {
stdout_eof = true;
}
if let Some(l) = stderr_line {
stderr_lines.push(l.clone());
stdcombined_lines.push(l);
} else {
stderr_eof = true;
}
if stderr_eof && stdout_eof { break; }
}
let res = ProcessOutput::new(
stdout_lines,
stderr_lines,
stdcombined_lines
);
return Ok(res);
}
Err(UECOError::Unknown)
}