Skip to content

NetBSD: add sysctl backend for std::env::current_exe #46373

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 2, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 28 additions & 1 deletion src/libstd/sys/unix/os.rs
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,34 @@ pub fn current_exe() -> io::Result<PathBuf> {

#[cfg(target_os = "netbsd")]
pub fn current_exe() -> io::Result<PathBuf> {
::fs::read_link("/proc/curproc/exe")
fn sysctl() -> io::Result<PathBuf> {
unsafe {
let mib = [libc::CTL_KERN, libc::KERN_PROC_ARGS, -1, libc::KERN_PROC_PATHNAME];
let mut path_len: usize = 0;
cvt(libc::sysctl(mib.as_ptr(), mib.len() as ::libc::c_uint,
ptr::null_mut(), &mut path_len,
ptr::null(), 0))?;
if path_len <= 1 {
return Err(io::Error::new(io::ErrorKind::Other,
"KERN_PROC_PATHNAME sysctl returned zero-length string"))
}
let mut path: Vec<u8> = Vec::with_capacity(path_len);
cvt(libc::sysctl(mib.as_ptr(), mib.len() as ::libc::c_uint,
path.as_ptr() as *mut libc::c_void, &mut path_len,
ptr::null(), 0))?;
path.set_len(path_len - 1); // chop off NUL
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you need to check path_len == 0 just like the FreeBSD implementation above? Or is it possible to merge the implementations of the BSDs (only the mib differ as far as I can see).

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Possibly could even check for path_len <= 1 for additional safety. There are a few very subtle differences between the FreeBSD & DragonFly block and what I implemented, but I imagine they could be merged if thought best. While they are nearly identical, I have this purist view that as there is no shared lineage in the kernel-side implementation of these sysctls, they may as well stay seperate here.

Ok(PathBuf::from(OsString::from_vec(path)))
}
}
fn procfs() -> io::Result<PathBuf> {
let curproc_exe = path::Path::new("/proc/curproc/exe");
if curproc_exe.is_file() {
return ::fs::read_link(curproc_exe);
}
Err(io::Error::new(io::ErrorKind::Other,
"/proc/curproc/exe doesn't point to regular file."))
}
sysctl().or_else(|_| procfs())
}

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