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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
extern crate alloc;
use super::{
Error, ExitCode,
io::{self, Write as _},
};
#[cfg(target_os = "openbsd")]
use super::{Permissions, Promises, env};
use alloc::string::FromUtf8Error;
#[cfg(target_os = "openbsd")]
use std::{ffi::OsStr, fs, io::ErrorKind};
use std::{
path::{Path, PathBuf},
process::{Command, Stdio},
};
/// Error when executing `rustc -Whelp`.
pub(crate) enum E {
/// I/O error.
Io(Error),
/// Error when there is no `$PATH` variable.
#[cfg(target_os = "openbsd")]
NoPathVariable,
/// Error when `"rustc"` is unable to be located in `$PATH`.
#[cfg(target_os = "openbsd")]
NoRustcInPath,
/// `rustc -Whelp` didn't return a status code, and nothing was written to `stderr`.
RustcNoStatusNoErr,
/// `rustc -Whelp` didn't return a status code, and invalid UTF-8 was written to `stderr`.
RustcNoStatusInvalidUtf8(FromUtf8Error),
/// `rustc -Whelp` didn't return a status code, and the contained `String` was written to `stderr`.
RustcNoStatusErr(String),
/// `rustc -Whelp` returned an error code, but nothing was written to `stderr`.
RustcErrStatusNoErr(i32),
/// `rustc -Whelp` returned an error code, but `stderr` contained invalid UTF-8.
RustcErrStatusInvalidUtf8(i32, FromUtf8Error),
/// `rustc -Whelp` returned an error code, and the contained `String` was written to `stderr`.
RustcErrStatus(i32, String),
/// `rustc -Whelp` returned a success code, but `stderr` contained invalid UTF-8.
RustcSuccessErrInvalidUtf8(FromUtf8Error),
/// `rustc -Whelp` returned a success code, but the contained `String` was written to `stderr`.
RustcSuccessErr(String),
}
impl E {
/// Writes `self` into `stderr`.
pub(crate) fn into_exit_code(self) -> ExitCode {
let mut stderr = io::stderr().lock();
match self {
Self::Io(err) => writeln!(stderr, "I/O issue: {err}."),
#[cfg(target_os = "openbsd")]
Self::NoPathVariable => writeln!(
stderr,
"No PATH variable."
),
#[cfg(target_os = "openbsd")]
Self::NoRustcInPath => writeln!(
stderr,
"rustc could not be found based on the PATH variable."
),
Self::RustcNoStatusNoErr => writeln!(
stderr,
"rustc -Whelp didn't return a status code but didn't write anything to stderr."
),
Self::RustcNoStatusInvalidUtf8(err) => writeln!(
stderr,
"rustc -Whelp didn't return a status code, but stderr contained invalid UTF-8: {err}."
),
Self::RustcNoStatusErr(err) => writeln!(
stderr,
"rustc -Whelp didn't return a status code, and the following was written to stderr: {err}."
),
Self::RustcErrStatusNoErr(code) => writeln!(
stderr,
"rustc -Whelp returned status {code}, but didn't write anything to stderr."
),
Self::RustcErrStatusInvalidUtf8(code, err) => writeln!(
stderr,
"rustc -Whelp returned status {code}, but stderr contained invalid UTF-8: {err}."
),
Self::RustcErrStatus(code, err) => writeln!(
stderr,
"rustc -Whelp returned status {code}, and the following was written to stderr: {err}."
),
Self::RustcSuccessErrInvalidUtf8(err) => writeln!(
stderr,
"rustc -Whelp returned a successful status code, but stderr contained invalid UTF-8: {err}."
),
Self::RustcSuccessErr(err) => writeln!(
stderr,
"rustc -Whelp returned a successful status code, but the following was written to stderr: {err}."
),
}.map_or(ExitCode::FAILURE, |()| ExitCode::FAILURE)
}
}
/// `"rustc"`.
const RUSTC: &str = "rustc";
/// Returns [`RUSTC`] as a `PathBuf`.
#[expect(clippy::unnecessary_wraps, reason = "unify with OpenBSD")]
#[cfg(not(target_os = "openbsd"))]
fn priv_sep<Never>() -> Result<PathBuf, Never> {
Ok(RUSTC.into())
}
/// `unveil(2)`s the file system for read-only permissions.
/// Traverses `$PATH` to find `"rustc"`; when found, removes read permissions on the file system before
/// `unveil(2)`ing `"rustc"` with execute permissions. Last, `pledge(2)`s `c"exec proc stdio unveil"`.
#[expect(unsafe_code, reason = "comment justifies correctness")]
#[expect(clippy::option_if_let_else, reason = "false positive")]
#[cfg(target_os = "openbsd")]
fn priv_sep() -> Result<PathBuf, E> {
Permissions::unveil_raw(c"/", c"r")
.map_err(|e| E::Io(e.into()))
.and_then(|()| {
env::var_os("PATH").map_or(Err(E::NoPathVariable), |path| {
path.as_encoded_bytes()
.split(|b| *b == b':')
.try_fold((), |(), dir| {
// SAFETY:
// `dir` is obtained directly from `path.as_encoded_bytes` with at most a single
// `b':'` removed ensuring any valid UTF-8 that existed before still does.
let dir_os = unsafe { OsStr::from_encoded_bytes_unchecked(dir) };
fs::read_dir(dir_os).map_or_else(
|e| {
if matches!(e.kind(), ErrorKind::NotADirectory) {
let val = PathBuf::from(dir_os);
match val.file_name() {
None => Ok(()),
Some(file) => {
if file == RUSTC {
Err(val)
} else {
Ok(())
}
}
}
} else {
Ok(())
}
},
|mut ents| {
ents.try_fold((), |(), ent_res| {
ent_res.map_or(Ok(()), |ent| {
if ent.file_name() == RUSTC {
Err(PathBuf::from(dir_os).join(RUSTC))
} else {
Ok(())
}
})
})
},
)
})
.map_or_else(
|rustc| {
Permissions::unveil_raw(c"/", c"")
.and_then(|()| {
Permissions::unveil_raw(&rustc, c"x").and_then(|()| {
Promises::pledge_raw(c"exec proc stdio unveil")
.map(|()| rustc)
})
})
.map_err(|e| E::Io(e.into()))
},
|()| Err(E::NoRustcInPath),
)
})
})
}
/// No-op.
#[expect(clippy::unnecessary_wraps, reason = "unify with OpenBSD")]
#[cfg(not(target_os = "openbsd"))]
const fn priv_sep_final<Never>(_: &Path) -> Result<(), Never> {
Ok(())
}
/// Removes execute permissions on `path` before `pledge(2)`ing `c"stdio"`.
#[cfg(target_os = "openbsd")]
fn priv_sep_final(path: &Path) -> Result<(), E> {
Permissions::unveil_raw(path, c"")
.and_then(|()| Promises::pledge_raw(c"stdio"))
.map_err(|e| E::Io(e.into()))
}
/// Gets output of `rustc -Whelp`.
pub(crate) fn execute_rustc() -> Result<Vec<u8>, E> {
priv_sep().and_then(|path| {
Command::new(&path)
.arg("-Whelp")
.stderr(Stdio::piped())
.stdin(Stdio::null())
.stdout(Stdio::piped())
.output()
.map_err(E::Io)
.and_then(|output| {
priv_sep_final(&path).and_then(|()| match output.status.code() {
None => {
if output.stderr.is_empty() {
Err(E::RustcNoStatusNoErr)
} else {
String::from_utf8(output.stderr)
.map_err(E::RustcNoStatusInvalidUtf8)
.and_then(|err| Err(E::RustcNoStatusErr(err)))
}
}
Some(code) => {
if code == 0i32 {
if output.stderr.is_empty() {
Ok(output.stdout)
} else {
String::from_utf8(output.stderr)
.map_err(E::RustcSuccessErrInvalidUtf8)
.and_then(|err| Err(E::RustcSuccessErr(err)))
}
} else if output.stderr.is_empty() {
Err(E::RustcErrStatusNoErr(code))
} else {
String::from_utf8(output.stderr)
.map_err(|err| E::RustcErrStatusInvalidUtf8(code, err))
.and_then(|err| Err(E::RustcErrStatus(code, err)))
}
}
})
})
})
}
#[cfg(test)]
mod tests {
#[cfg(not(target_os = "openbsd"))]
use core::convert::Infallible;
#[cfg(target_os = "openbsd")]
use std::ffi::OsString;
#[test]
#[cfg(not(target_os = "openbsd"))]
fn priv_sep() {
assert_eq!(super::priv_sep::<Infallible>(), Ok("rustc".into()));
}
#[ignore = "interferes with testing. should run separately to avoid issues."]
#[test]
#[cfg(target_os = "openbsd")]
fn priv_sep() {
assert!(super::priv_sep().is_ok_and(
|path| path.is_absolute() && path.file_name() == Some(&OsString::from("rustc"))
));
}
}