Skip to content

Commit ccef969

Browse files
committedNov 30, 2017
NetBSD: add sysctl backend for std::env::current_exe
Use the CTL_KERN.KERN_PROC_ARGS.-1.KERN_PROC_PATHNAME sysctl in preference over the /proc/curproc/exe symlink. Additionally, perform more validation of aformentioned symlink. Particularly on pre-8.x NetBSD this symlink will point to '/' when accurate information is unavailable.
1 parent 4fa202d commit ccef969

File tree

1 file changed

+28
-1
lines changed

1 file changed

+28
-1
lines changed
 

‎src/libstd/sys/unix/os.rs

+28-1
Original file line numberDiff line numberDiff line change
@@ -223,7 +223,34 @@ pub fn current_exe() -> io::Result<PathBuf> {
223223

224224
#[cfg(target_os = "netbsd")]
225225
pub fn current_exe() -> io::Result<PathBuf> {
226-
::fs::read_link("/proc/curproc/exe")
226+
fn sysctl() -> io::Result<PathBuf> {
227+
unsafe {
228+
let mib = [libc::CTL_KERN, libc::KERN_PROC_ARGS, -1, libc::KERN_PROC_PATHNAME];
229+
let mut path_len: usize = 0;
230+
cvt(libc::sysctl(mib.as_ptr(), mib.len() as ::libc::c_uint,
231+
ptr::null_mut(), &mut path_len,
232+
ptr::null(), 0))?;
233+
if path_len <= 1 {
234+
return Err(io::Error::new(io::ErrorKind::Other,
235+
"KERN_PROC_PATHNAME sysctl returned zero-length string"))
236+
}
237+
let mut path: Vec<u8> = Vec::with_capacity(path_len);
238+
cvt(libc::sysctl(mib.as_ptr(), mib.len() as ::libc::c_uint,
239+
path.as_ptr() as *mut libc::c_void, &mut path_len,
240+
ptr::null(), 0))?;
241+
path.set_len(path_len - 1); // chop off NUL
242+
Ok(PathBuf::from(OsString::from_vec(path)))
243+
}
244+
}
245+
fn procfs() -> io::Result<PathBuf> {
246+
let curproc_exe = path::Path::new("/proc/curproc/exe");
247+
if curproc_exe.is_file() {
248+
return ::fs::read_link(curproc_exe);
249+
}
250+
Err(io::Error::new(io::ErrorKind::Other,
251+
"/proc/curproc/exe doesn't point to regular file."))
252+
}
253+
sysctl().or_else(|_| procfs())
227254
}
228255

229256
#[cfg(any(target_os = "bitrig", target_os = "openbsd"))]

0 commit comments

Comments
 (0)
Please sign in to comment.