Skip to content
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

env::temp_dir returns /private/tmp on Apple instead while /tmp is #100196

Closed
wants to merge 2 commits into from
Closed
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
30 changes: 30 additions & 0 deletions library/std/src/sys/unix/os.rs
Original file line number Diff line number Diff line change
Expand Up @@ -586,6 +586,36 @@ pub fn temp_dir() -> PathBuf {
crate::env::var_os("TMPDIR").map(PathBuf::from).unwrap_or_else(|| {
if cfg!(target_os = "android") {
PathBuf::from("/data/local/tmp")
} else if cfg!(target_vendor = "apple") {
extern "C" {
fn confstr(
name: libc::c_int,
buf: *mut libc::c_char,
len: libc::size_t,
) -> libc::size_t;
}
let tmpdir = unsafe { libc::getenv(b"TMPDIR".as_ptr() as *const libc::c_char) };
Copy link
Member

Choose a reason for hiding this comment

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

We already checked the env above. Also, don't use libc::getenv as it doesn't hold the env lock. Also, this string isn't NUL-terminated.

if tmpdir.is_null() {
let mut buf: Vec<u8> = vec![0; libc::PATH_MAX as usize];
Copy link
Member

Choose a reason for hiding this comment

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

50 bytes should be enough in practice, but really this should have some retry logic. I was going to submit thomcc@ee1c648 as a PR at one point, but you can just integrate the changes from it.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

it s better if you do since you authored all.

const _CS_DARWIN_USER_TEMP_DIR: libc::c_int = 65537;
Copy link
Member

Choose a reason for hiding this comment

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

Let's wait for rust-lang/libc#2883.

let s = unsafe {
confstr(
_CS_DARWIN_USER_TEMP_DIR,
buf.as_mut_ptr() as *mut libc::c_char,
libc::PATH_MAX as usize,
)
};
if s == 0 {
return PathBuf::from("/private/tmp");
}
let l = buf.iter().position(|&c| c == 0).unwrap();
buf.truncate(l as usize);
buf.shrink_to_fit();
return PathBuf::from(OsString::from_vec(buf));
}

let p = unsafe { CStr::from_ptr(tmpdir).to_bytes().to_vec() };
PathBuf::from(OsString::from_vec(p))
} else {
PathBuf::from("/tmp")
}
Expand Down