1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Implementation of `std::os` functionality for unix systems
13 #![allow(unused_imports)] // lots of cfg code here
15 use os
::unix
::prelude
::*;
17 use error
::Error
as StdError
;
18 use ffi
::{CString, CStr, OsString, OsStr}
;
22 use libc
::{self, c_int, c_char, c_void}
;
23 use marker
::PhantomData
;
26 use path
::{self, PathBuf}
;
30 use sys_common
::mutex
::Mutex
;
35 const TMPBUF_SZ
: usize = 128;
36 static ENV_LOCK
: Mutex
= Mutex
::new();
40 #[cfg(not(target_os = "dragonfly"))]
41 #[cfg_attr(any(target_os = "linux", target_os = "emscripten", target_os = "fuchsia"),
42 link_name
= "__errno_location")]
43 #[cfg_attr(any(target_os = "bitrig",
45 target_os
= "openbsd",
46 target_os
= "android",
47 target_env
= "newlib"),
48 link_name
= "__errno")]
49 #[cfg_attr(target_os = "solaris", link_name = "___errno")]
50 #[cfg_attr(any(target_os = "macos",
52 target_os
= "freebsd"),
53 link_name
= "__error")]
54 #[cfg_attr(target_os = "haiku", link_name = "_errnop")]
55 fn errno_location() -> *mut c_int
;
58 /// Returns the platform-specific value of errno
59 #[cfg(not(target_os = "dragonfly"))]
60 pub fn errno() -> i32 {
62 (*errno_location()) as i32
66 /// Sets the platform-specific value of errno
67 #[cfg(target_os = "solaris")] // only needed for readdir so far
68 pub fn set_errno(e
: i32) {
70 *errno_location() = e
as c_int
74 #[cfg(target_os = "dragonfly")]
75 pub fn errno() -> i32 {
84 /// Gets a detailed string description for the given error number.
85 pub fn error_string(errno
: i32) -> String
{
87 #[cfg_attr(any(target_os = "linux", target_env = "newlib"),
88 link_name
= "__xpg_strerror_r")]
89 fn strerror_r(errnum
: c_int
, buf
: *mut c_char
,
90 buflen
: libc
::size_t
) -> c_int
;
93 let mut buf
= [0 as c_char
; TMPBUF_SZ
];
95 let p
= buf
.as_mut_ptr();
97 if strerror_r(errno
as c_int
, p
, buf
.len()) < 0 {
98 panic
!("strerror_r failure");
101 let p
= p
as *const _
;
102 str::from_utf8(CStr
::from_ptr(p
).to_bytes()).unwrap().to_owned()
106 pub fn getcwd() -> io
::Result
<PathBuf
> {
107 let mut buf
= Vec
::with_capacity(512);
110 let ptr
= buf
.as_mut_ptr() as *mut libc
::c_char
;
111 if !libc
::getcwd(ptr
, buf
.capacity()).is_null() {
112 let len
= CStr
::from_ptr(buf
.as_ptr() as *const libc
::c_char
).to_bytes().len();
115 return Ok(PathBuf
::from(OsString
::from_vec(buf
)));
117 let error
= io
::Error
::last_os_error();
118 if error
.raw_os_error() != Some(libc
::ERANGE
) {
123 // Trigger the internal buffer resizing logic of `Vec` by requiring
124 // more space than the current capacity.
125 let cap
= buf
.capacity();
132 pub fn chdir(p
: &path
::Path
) -> io
::Result
<()> {
133 let p
: &OsStr
= p
.as_ref();
134 let p
= CString
::new(p
.as_bytes())?
;
136 match libc
::chdir(p
.as_ptr()) == (0 as c_int
) {
138 false => Err(io
::Error
::last_os_error()),
143 pub struct SplitPaths
<'a
> {
144 iter
: iter
::Map
<slice
::Split
<'a
, u8, fn(&u8) -> bool
>,
145 fn(&'a
[u8]) -> PathBuf
>,
148 pub fn split_paths(unparsed
: &OsStr
) -> SplitPaths
{
149 fn bytes_to_path(b
: &[u8]) -> PathBuf
{
150 PathBuf
::from(<OsStr
as OsStrExt
>::from_bytes(b
))
152 fn is_colon(b
: &u8) -> bool { *b == b':' }
153 let unparsed
= unparsed
.as_bytes();
155 iter
: unparsed
.split(is_colon
as fn(&u8) -> bool
)
156 .map(bytes_to_path
as fn(&[u8]) -> PathBuf
)
160 impl<'a
> Iterator
for SplitPaths
<'a
> {
162 fn next(&mut self) -> Option
<PathBuf
> { self.iter.next() }
163 fn size_hint(&self) -> (usize, Option
<usize>) { self.iter.size_hint() }
167 pub struct JoinPathsError
;
169 pub fn join_paths
<I
, T
>(paths
: I
) -> Result
<OsString
, JoinPathsError
>
170 where I
: Iterator
<Item
=T
>, T
: AsRef
<OsStr
>
172 let mut joined
= Vec
::new();
175 for (i
, path
) in paths
.enumerate() {
176 let path
= path
.as_ref().as_bytes();
177 if i
> 0 { joined.push(sep) }
178 if path
.contains(&sep
) {
179 return Err(JoinPathsError
)
181 joined
.extend_from_slice(path
);
183 Ok(OsStringExt
::from_vec(joined
))
186 impl fmt
::Display
for JoinPathsError
{
187 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
188 "path segment contains separator `:`".fmt(f
)
192 impl StdError
for JoinPathsError
{
193 fn description(&self) -> &str { "failed to join paths" }
196 #[cfg(target_os = "freebsd")]
197 pub fn current_exe() -> io
::Result
<PathBuf
> {
199 let mut mib
= [libc
::CTL_KERN
as c_int
,
200 libc
::KERN_PROC
as c_int
,
201 libc
::KERN_PROC_PATHNAME
as c_int
,
204 cvt(libc
::sysctl(mib
.as_mut_ptr(), mib
.len() as ::libc
::c_uint
,
205 ptr
::null_mut(), &mut sz
, ptr
::null_mut(), 0))?
;
207 return Err(io
::Error
::last_os_error())
209 let mut v
: Vec
<u8> = Vec
::with_capacity(sz
);
210 cvt(libc
::sysctl(mib
.as_mut_ptr(), mib
.len() as ::libc
::c_uint
,
211 v
.as_mut_ptr() as *mut libc
::c_void
, &mut sz
,
212 ptr
::null_mut(), 0))?
;
214 return Err(io
::Error
::last_os_error());
216 v
.set_len(sz
- 1); // chop off trailing NUL
217 Ok(PathBuf
::from(OsString
::from_vec(v
)))
221 #[cfg(target_os = "dragonfly")]
222 pub fn current_exe() -> io
::Result
<PathBuf
> {
223 ::fs
::read_link("/proc/curproc/file")
226 #[cfg(target_os = "netbsd")]
227 pub fn current_exe() -> io
::Result
<PathBuf
> {
228 ::fs
::read_link("/proc/curproc/exe")
231 #[cfg(any(target_os = "bitrig", target_os = "openbsd"))]
232 pub fn current_exe() -> io
::Result
<PathBuf
> {
234 let mut mib
= [libc
::CTL_KERN
,
235 libc
::KERN_PROC_ARGS
,
237 libc
::KERN_PROC_ARGV
];
238 let mib
= mib
.as_mut_ptr();
239 let mut argv_len
= 0;
240 cvt(libc
::sysctl(mib
, 4, ptr
::null_mut(), &mut argv_len
,
241 ptr
::null_mut(), 0))?
;
242 let mut argv
= Vec
::<*const libc
::c_char
>::with_capacity(argv_len
as usize);
243 cvt(libc
::sysctl(mib
, 4, argv
.as_mut_ptr() as *mut _
,
244 &mut argv_len
, ptr
::null_mut(), 0))?
;
245 argv
.set_len(argv_len
as usize);
246 if argv
[0].is_null() {
247 return Err(io
::Error
::new(io
::ErrorKind
::Other
,
248 "no current exe available"))
250 let argv0
= CStr
::from_ptr(argv
[0]).to_bytes();
251 if argv0
[0] == b'
.'
|| argv0
.iter().any(|b
| *b
== b'
/'
) {
252 ::fs
::canonicalize(OsStr
::from_bytes(argv0
))
254 Ok(PathBuf
::from(OsStr
::from_bytes(argv0
)))
259 #[cfg(any(target_os = "linux", target_os = "android", target_os = "emscripten"))]
260 pub fn current_exe() -> io
::Result
<PathBuf
> {
261 ::fs
::read_link("/proc/self/exe")
264 #[cfg(any(target_os = "macos", target_os = "ios"))]
265 pub fn current_exe() -> io
::Result
<PathBuf
> {
267 fn _NSGetExecutablePath(buf
: *mut libc
::c_char
,
268 bufsize
: *mut u32) -> libc
::c_int
;
272 _NSGetExecutablePath(ptr
::null_mut(), &mut sz
);
273 if sz
== 0 { return Err(io::Error::last_os_error()); }
274 let mut v
: Vec
<u8> = Vec
::with_capacity(sz
as usize);
275 let err
= _NSGetExecutablePath(v
.as_mut_ptr() as *mut i8, &mut sz
);
276 if err
!= 0 { return Err(io::Error::last_os_error()); }
277 v
.set_len(sz
as usize - 1); // chop off trailing NUL
278 Ok(PathBuf
::from(OsString
::from_vec(v
)))
282 #[cfg(any(target_os = "solaris"))]
283 pub fn current_exe() -> io
::Result
<PathBuf
> {
285 fn getexecname() -> *const c_char
;
288 let path
= getexecname();
290 Err(io
::Error
::last_os_error())
292 let filename
= CStr
::from_ptr(path
).to_bytes();
293 let path
= PathBuf
::from(<OsStr
as OsStrExt
>::from_bytes(filename
));
295 // Prepend a current working directory to the path if
296 // it doesn't contain an absolute pathname.
297 if filename
[0] == b'
/'
{
300 getcwd().map(|cwd
| cwd
.join(path
))
306 #[cfg(target_os = "haiku")]
307 pub fn current_exe() -> io
::Result
<PathBuf
> {
308 // Use Haiku's image info functions
315 init_routine
: *mut libc
::c_void
, // function pointer
316 term_routine
: *mut libc
::c_void
, // function pointer
319 name
: [libc
::c_char
; 1024], // MAXPATHLEN
320 text
: *mut libc
::c_void
,
321 data
: *mut libc
::c_void
,
330 fn _get_next_image_info(team_id
: i32, cookie
: *mut i32,
331 info
: *mut image_info
, size
: i32) -> i32;
334 let mut info
: image_info
= mem
::zeroed();
335 let mut cookie
: i32 = 0;
336 // the executable can be found at team id 0
337 let result
= _get_next_image_info(0, &mut cookie
, &mut info
,
338 mem
::size_of
::<image_info
>() as i32);
341 Err(io
::Error
::new(ErrorKind
::Other
, "Error getting executable path"))
343 let name
= CStr
::from_ptr(info
.name
.as_ptr()).to_bytes();
344 Ok(PathBuf
::from(OsStr
::from_bytes(name
)))
349 #[cfg(target_os = "fuchsia")]
350 pub fn current_exe() -> io
::Result
<PathBuf
> {
352 Err(io
::Error
::new(ErrorKind
::Other
, "Not yet implemented on fuchsia"))
356 iter
: vec
::IntoIter
<(OsString
, OsString
)>,
357 _dont_send_or_sync_me
: PhantomData
<*mut ()>,
360 impl Iterator
for Env
{
361 type Item
= (OsString
, OsString
);
362 fn next(&mut self) -> Option
<(OsString
, OsString
)> { self.iter.next() }
363 fn size_hint(&self) -> (usize, Option
<usize>) { self.iter.size_hint() }
366 #[cfg(target_os = "macos")]
367 pub unsafe fn environ() -> *mut *const *const c_char
{
368 extern { fn _NSGetEnviron() -> *mut *const *const c_char; }
372 #[cfg(not(target_os = "macos"))]
373 pub unsafe fn environ() -> *mut *const *const c_char
{
374 extern { static mut environ: *const *const c_char; }
378 /// Returns a vector of (variable, value) byte-vector pairs for all the
379 /// environment variables of the current process.
380 pub fn env() -> Env
{
383 let mut environ
= *environ();
384 if environ
== ptr
::null() {
386 panic
!("os::env() failure getting env string from OS: {}",
387 io
::Error
::last_os_error());
389 let mut result
= Vec
::new();
390 while *environ
!= ptr
::null() {
391 if let Some(key_value
) = parse(CStr
::from_ptr(*environ
).to_bytes()) {
392 result
.push(key_value
);
394 environ
= environ
.offset(1);
397 iter
: result
.into_iter(),
398 _dont_send_or_sync_me
: PhantomData
,
404 fn parse(input
: &[u8]) -> Option
<(OsString
, OsString
)> {
405 // Strategy (copied from glibc): Variable name and value are separated
406 // by an ASCII equals sign '='. Since a variable name must not be
407 // empty, allow variable names starting with an equals sign. Skip all
409 if input
.is_empty() {
412 let pos
= memchr
::memchr(b'
='
, &input
[1..]).map(|p
| p
+ 1);
414 OsStringExt
::from_vec(input
[..p
].to_vec()),
415 OsStringExt
::from_vec(input
[p
+1..].to_vec()),
420 pub fn getenv(k
: &OsStr
) -> io
::Result
<Option
<OsString
>> {
421 // environment variables with a nul byte can't be set, so their value is
422 // always None as well
423 let k
= CString
::new(k
.as_bytes())?
;
426 let s
= libc
::getenv(k
.as_ptr()) as *const _
;
427 let ret
= if s
.is_null() {
430 Some(OsStringExt
::from_vec(CStr
::from_ptr(s
).to_bytes().to_vec()))
437 pub fn setenv(k
: &OsStr
, v
: &OsStr
) -> io
::Result
<()> {
438 let k
= CString
::new(k
.as_bytes())?
;
439 let v
= CString
::new(v
.as_bytes())?
;
443 let ret
= cvt(libc
::setenv(k
.as_ptr(), v
.as_ptr(), 1)).map(|_
| ());
449 pub fn unsetenv(n
: &OsStr
) -> io
::Result
<()> {
450 let nbuf
= CString
::new(n
.as_bytes())?
;
454 let ret
= cvt(libc
::unsetenv(nbuf
.as_ptr())).map(|_
| ());
460 pub fn page_size() -> usize {
462 libc
::sysconf(libc
::_SC_PAGESIZE
) as usize
466 pub fn temp_dir() -> PathBuf
{
467 ::env
::var_os("TMPDIR").map(PathBuf
::from
).unwrap_or_else(|| {
468 if cfg
!(target_os
= "android") {
469 PathBuf
::from("/data/local/tmp")
471 PathBuf
::from("/tmp")
476 pub fn home_dir() -> Option
<PathBuf
> {
477 return ::env
::var_os("HOME").or_else(|| unsafe {
479 }).map(PathBuf
::from
);
481 #[cfg(any(target_os = "android",
484 target_os
= "emscripten"))]
485 unsafe fn fallback() -> Option
<OsString
> { None }
486 #[cfg(not(any(target_os = "android",
489 target_os
= "emscripten")))]
490 unsafe fn fallback() -> Option
<OsString
> {
491 #[cfg(not(target_os = "solaris"))]
492 unsafe fn getpwduid_r(me
: libc
::uid_t
, passwd
: &mut libc
::passwd
,
493 buf
: &mut Vec
<c_char
>) -> Option
<()> {
494 let mut result
= ptr
::null_mut();
495 match libc
::getpwuid_r(me
, passwd
, buf
.as_mut_ptr(),
498 0 if !result
.is_null() => Some(()),
503 #[cfg(target_os = "solaris")]
504 unsafe fn getpwduid_r(me
: libc
::uid_t
, passwd
: &mut libc
::passwd
,
505 buf
: &mut Vec
<c_char
>) -> Option
<()> {
506 // getpwuid_r semantics is different on Illumos/Solaris:
507 // http://illumos.org/man/3c/getpwuid_r
508 let result
= libc
::getpwuid_r(me
, passwd
, buf
.as_mut_ptr(),
510 if result
.is_null() { None }
else { Some(()) }
513 let amt
= match libc
::sysconf(libc
::_SC_GETPW_R_SIZE_MAX
) {
514 n
if n
< 0 => 512 as usize,
517 let mut buf
= Vec
::with_capacity(amt
);
518 let mut passwd
: libc
::passwd
= mem
::zeroed();
520 if getpwduid_r(libc
::getuid(), &mut passwd
, &mut buf
).is_some() {
521 let ptr
= passwd
.pw_dir
as *const _
;
522 let bytes
= CStr
::from_ptr(ptr
).to_bytes().to_vec();
523 Some(OsStringExt
::from_vec(bytes
))
530 pub fn exit(code
: i32) -> ! {
531 unsafe { libc::exit(code as c_int) }