os.rs 68.0 KB
Newer Older
1
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 3 4 5 6 7 8 9 10
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
/*!
 * Higher-level interfaces to libc::* functions and operating system services.
 *
 * In general these take and return rust types, use rust idioms (enums,
 * closures, vectors) rather than C idioms, and do more extensive safety
 * checks.
 *
 * This module is not meant to only contain 1:1 mappings to libc entries; any
 * os-interface code that is reasonably useful and broadly applicable can go
 * here. Including utility routines that merely build on other os code.
 *
 * We assume the general case is that users do not care, and do not want to
 * be made to care, which operating system they are on. While they may want
 * to special case various special cases -- and so we will not _hide_ the
 * facts of which OS the user is on -- they should be given the opportunity
 * to write OS-ignorant code by default.
 */
28

29 30
#![experimental]

31
#![allow(missing_doc)]
32
#![allow(non_snake_case_functions)]
33

34
use clone::Clone;
35
use collections::Collection;
36
use fmt;
37
use io::{IoResult, IoError};
38
use iter::Iterator;
39
use libc::{c_void, c_int};
40 41
use libc;
use ops::Drop;
42
use option::{Some, None, Option};
43
use os;
A
Aaron Turon 已提交
44
use path::{Path, GenericPath, BytesContainer};
45
use ptr::RawPtr;
46
use ptr;
47
use result::{Err, Ok, Result};
48
use slice::{Vector, ImmutableVector, MutableVector, ImmutableEqVector};
49
use str::{Str, StrSlice, StrAllocating};
50
use str;
51
use string::String;
52
use sync::atomics::{AtomicInt, INIT_ATOMIC_INT, SeqCst};
53
use vec::Vec;
54 55 56

#[cfg(unix)]
use c_str::ToCStr;
57 58
#[cfg(unix)]
use libc::c_char;
59 60
#[cfg(windows)]
use str::OwnedStr;
61

62 63 64 65 66 67 68 69 70 71
/// Get the number of cores available
pub fn num_cpus() -> uint {
    unsafe {
        return rust_get_num_cpus();
    }

    extern {
        fn rust_get_num_cpus() -> libc::uintptr_t;
    }
}
72

73 74
pub static TMPBUF_SZ : uint = 1000u;
static BUF_BYTES : uint = 2048u;
75

76 77 78 79 80 81 82 83 84 85 86 87 88
/// Returns the current working directory as a Path.
///
/// # Failure
///
/// Fails if the current working directory value is invalid:
/// Possibles cases:
///
/// * Current directory does not exist.
/// * There are insufficient permissions to access the current directory.
///
/// # Example
///
/// ```rust
A
Axel Viala 已提交
89 90
/// use std::os;
///
91
/// // We assume that we are in a valid directory like "/home".
A
Axel Viala 已提交
92
/// let current_working_directory = os::getcwd();
93 94 95
/// println!("The current directory is {}", current_working_directory.display());
/// // /home
/// ```
96
#[cfg(unix)]
97
pub fn getcwd() -> Path {
98 99
    use c_str::CString;

100
    let mut buf = [0 as c_char, ..BUF_BYTES];
101
    unsafe {
A
Alex Crichton 已提交
102
        if libc::getcwd(buf.as_mut_ptr(), buf.len() as libc::size_t).is_null() {
103
            fail!()
104
        }
105 106
        Path::new(CString::new(buf.as_ptr(), false))
    }
107 108
}

109 110 111 112 113 114 115 116 117 118 119 120 121
/// Returns the current working directory as a Path.
///
/// # Failure
///
/// Fails if the current working directory value is invalid.
/// Possibles cases:
///
/// * Current directory does not exist.
/// * There are insufficient permissions to access the current directory.
///
/// # Example
///
/// ```rust
A
Axel Viala 已提交
122 123
/// use std::os;
///
124
/// // We assume that we are in a valid directory like "C:\\Windows".
A
Axel Viala 已提交
125
/// let current_working_directory = os::getcwd();
126 127 128
/// println!("The current directory is {}", current_working_directory.display());
/// // C:\\Windows
/// ```
129 130 131 132
#[cfg(windows)]
pub fn getcwd() -> Path {
    use libc::DWORD;
    use libc::GetCurrentDirectoryW;
A
Alex Crichton 已提交
133

134
    let mut buf = [0 as u16, ..BUF_BYTES];
135 136 137
    unsafe {
        if libc::GetCurrentDirectoryW(buf.len() as DWORD, buf.as_mut_ptr()) == 0 as DWORD {
            fail!();
138
        }
139
    }
A
Adolfo Ochagavía 已提交
140
    Path::new(String::from_utf16(str::truncate_utf16_at_nul(buf))
141
              .expect("GetCurrentDirectoryW returned invalid UTF-16"))
142 143
}

144
#[cfg(windows)]
145
pub mod win32 {
146
    use libc::types::os::arch::extra::DWORD;
147
    use libc;
148
    use option::{None, Option};
149
    use option;
150
    use os::TMPBUF_SZ;
A
Alex Crichton 已提交
151
    use slice::{MutableVector, ImmutableVector};
152
    use string::String;
153
    use str::StrSlice;
154
    use str;
155
    use vec::Vec;
156

157
    pub fn fill_utf16_buf_and_decode(f: |*mut u16, DWORD| -> DWORD)
158
        -> Option<String> {
159

160
        unsafe {
161
            let mut n = TMPBUF_SZ as DWORD;
162 163 164
            let mut res = None;
            let mut done = false;
            while !done {
165
                let mut buf = Vec::from_elem(n as uint, 0u16);
166
                let k = f(buf.as_mut_ptr(), n);
167 168
                if k == (0 as DWORD) {
                    done = true;
H
Huon Wilson 已提交
169 170 171
                } else if k == n &&
                          libc::GetLastError() ==
                          libc::ERROR_INSUFFICIENT_BUFFER as DWORD {
172
                    n *= 2 as DWORD;
173 174
                } else if k >= n {
                    n = k;
175 176 177
                } else {
                    done = true;
                }
178
                if k != 0 && done {
179
                    let sub = buf.slice(0, k as uint);
180 181 182
                    // We want to explicitly catch the case when the
                    // closure returned invalid UTF-16, rather than
                    // set `res` to None and continue.
A
Adolfo Ochagavía 已提交
183
                    let s = String::from_utf16(sub)
184 185
                        .expect("fill_utf16_buf_and_decode: closure created invalid UTF-16");
                    res = option::Some(s)
186
                }
187
            }
188
            return res;
189 190
        }
    }
191 192
}

193 194
/*
Accessing environment variables is not generally threadsafe.
195
Serialize access through a global lock.
196
*/
197
fn with_env_lock<T>(f: || -> T) -> T {
198
    use rt::mutex::{StaticNativeMutex, NATIVE_MUTEX_INIT};
199

200
    static mut lock: StaticNativeMutex = NATIVE_MUTEX_INIT;
201

202
    unsafe {
203 204
        let _guard = lock.lock();
        f()
205
    }
B
Ben Blum 已提交
206 207
}

A
Axel Viala 已提交
208 209
/// Returns a vector of (variable, value) pairs, for all the environment
/// variables of the current process.
210 211 212
///
/// Invalid UTF-8 bytes are replaced with \uFFFD. See `str::from_utf8_lossy()`
/// for details.
213 214 215 216
///
/// # Example
///
/// ```rust
A
Axel Viala 已提交
217 218 219 220
/// use std::os;
///
/// // We will iterate through the references to the element returned by os::env();
/// for &(ref key, ref value) in os::env().iter() {
221 222 223
///     println!("'{}': '{}'", key, value );
/// }
/// ```
224
pub fn env() -> Vec<(String,String)> {
225
    env_as_bytes().move_iter().map(|(k,v)| {
226 227
        let k = String::from_str(str::from_utf8_lossy(k.as_slice()).as_slice());
        let v = String::from_str(str::from_utf8_lossy(v.as_slice()).as_slice());
228 229 230 231 232 233
        (k,v)
    }).collect()
}

/// Returns a vector of (variable, value) byte-vector pairs for all the
/// environment variables of the current process.
234
pub fn env_as_bytes() -> Vec<(Vec<u8>,Vec<u8>)> {
235
    unsafe {
236
        #[cfg(windows)]
237
        unsafe fn get_env_pairs() -> Vec<Vec<u8>> {
238
            use slice::raw;
239

240
            use libc::funcs::extra::kernel32::{
241 242
                GetEnvironmentStringsW,
                FreeEnvironmentStringsW
243
            };
244
            let ch = GetEnvironmentStringsW();
H
Huon Wilson 已提交
245
            if ch as uint == 0 {
246
                fail!("os::env() failure getting env string from OS: {}",
A
Alex Crichton 已提交
247
                       os::last_os_error());
248
            }
249 250 251 252 253 254 255 256 257 258 259 260 261 262
            // Here, we lossily decode the string as UTF16.
            //
            // The docs suggest that the result should be in Unicode, but
            // Windows doesn't guarantee it's actually UTF16 -- it doesn't
            // validate the environment string passed to CreateProcess nor
            // SetEnvironmentVariable.  Yet, it's unlikely that returning a
            // raw u16 buffer would be of practical use since the result would
            // be inherently platform-dependent and introduce additional
            // complexity to this code.
            //
            // Using the non-Unicode version of GetEnvironmentStrings is even
            // worse since the result is in an OEM code page.  Characters that
            // can't be encoded in the code page would be turned into question
            // marks.
263
            let mut result = Vec::new();
264 265 266 267 268
            let mut i = 0;
            while *ch.offset(i) != 0 {
                let p = &*ch.offset(i);
                let len = ptr::position(p, |c| *c == 0);
                raw::buf_as_slice(p, len, |s| {
269
                    result.push(String::from_utf16_lossy(s).into_bytes());
270 271 272 273
                });
                i += len as int + 1;
            }
            FreeEnvironmentStringsW(ch);
274 275 276
            result
        }
        #[cfg(unix)]
277
        unsafe fn get_env_pairs() -> Vec<Vec<u8>> {
278 279
            use c_str::CString;

280
            extern {
281
                fn rust_env_pairs() -> *const *const c_char;
282
            }
283
            let environ = rust_env_pairs();
H
Huon Wilson 已提交
284
            if environ as uint == 0 {
285
                fail!("os::env() failure getting env string from OS: {}",
A
Alex Crichton 已提交
286
                       os::last_os_error());
287
            }
288
            let mut result = Vec::new();
289
            ptr::array_each(environ, |e| {
290 291
                let env_pair =
                    Vec::from_slice(CString::new(e, false).as_bytes_no_nul());
292 293 294 295 296
                result.push(env_pair);
            });
            result
        }

297
        fn env_convert(input: Vec<Vec<u8>>) -> Vec<(Vec<u8>, Vec<u8>)> {
298
            let mut pairs = Vec::new();
D
Daniel Micay 已提交
299
            for p in input.iter() {
300 301 302
                let mut it = p.as_slice().splitn(1, |b| *b == '=' as u8);
                let key = Vec::from_slice(it.next().unwrap());
                let val = Vec::from_slice(it.next().unwrap_or(&[]));
303
                pairs.push((key, val));
304
            }
L
Luqman Aden 已提交
305
            pairs
306
        }
307
        with_env_lock(|| {
308
            let unparsed_environ = get_env_pairs();
K
Kevin Ballard 已提交
309
            env_convert(unparsed_environ)
310
        })
311
    }
312
}
313

314
#[cfg(unix)]
315 316
/// Fetches the environment variable `n` from the current process, returning
/// None if the variable isn't set.
317 318 319 320 321 322 323
///
/// Any invalid UTF-8 bytes in the value are replaced by \uFFFD. See
/// `str::from_utf8_lossy()` for details.
///
/// # Failure
///
/// Fails if `n` has any interior NULs.
324 325 326 327
///
/// # Example
///
/// ```rust
A
Axel Viala 已提交
328 329
/// use std::os;
///
330
/// let key = "HOME";
A
Axel Viala 已提交
331
/// match os::getenv(key) {
332
///     Some(val) => println!("{}: {}", key, val),
J
Joseph Crail 已提交
333
///     None => println!("{} is not defined in the environment.", key)
334 335
/// }
/// ```
336
pub fn getenv(n: &str) -> Option<String> {
337
    getenv_as_bytes(n).map(|v| String::from_str(str::from_utf8_lossy(v.as_slice()).as_slice()))
338 339 340 341 342 343 344 345 346
}

#[cfg(unix)]
/// Fetches the environment variable `n` byte vector from the current process,
/// returning None if the variable isn't set.
///
/// # Failure
///
/// Fails if `n` has any interior NULs.
347
pub fn getenv_as_bytes(n: &str) -> Option<Vec<u8>> {
348 349
    use c_str::CString;

350
    unsafe {
351 352
        with_env_lock(|| {
            let s = n.with_c_str(|buf| libc::getenv(buf));
353
            if s.is_null() {
354
                None
355
            } else {
356
                Some(Vec::from_slice(CString::new(s as *const i8,
357
                                                  false).as_bytes_no_nul()))
358
            }
359
        })
360 361
    }
}
362

363
#[cfg(windows)]
364 365
/// Fetches the environment variable `n` from the current process, returning
/// None if the variable isn't set.
366
pub fn getenv(n: &str) -> Option<String> {
367
    unsafe {
368
        with_env_lock(|| {
369
            use os::win32::{fill_utf16_buf_and_decode};
J
John Schmidt 已提交
370 371
            let n: Vec<u16> = n.utf16_units().collect();
            let n = n.append_one(0);
372 373
            fill_utf16_buf_and_decode(|buf, sz| {
                libc::GetEnvironmentVariableW(n.as_ptr(), buf, sz)
374 375
            })
        })
376 377
    }
}
378

379 380 381
#[cfg(windows)]
/// Fetches the environment variable `n` byte vector from the current process,
/// returning None if the variable isn't set.
382
pub fn getenv_as_bytes(n: &str) -> Option<Vec<u8>> {
383 384 385
    getenv(n).map(|s| s.into_bytes())
}

386
/// Sets the environment variable `n` to the value `v` for the currently running
A
Axel Viala 已提交
387
/// process.
388
///
A
Axel Viala 已提交
389
/// # Example
390
///
A
Axel Viala 已提交
391 392 393 394 395 396 397 398 399 400
/// ```rust
/// use std::os;
///
/// let key = "KEY";
/// os::setenv(key, "VALUE");
/// match os::getenv(key) {
///     Some(ref val) => println!("{}: {}", key, val),
///     None => println!("{} is not defined in the environment.", key)
/// }
/// ```
401
pub fn setenv<T: BytesContainer>(n: &str, v: T) {
A
Axel Viala 已提交
402
    #[cfg(unix)]
403
    fn _setenv(n: &str, v: &[u8]) {
A
Axel Viala 已提交
404 405 406 407 408 409
        unsafe {
            with_env_lock(|| {
                n.with_c_str(|nbuf| {
                    v.with_c_str(|vbuf| {
                        libc::funcs::posix01::unistd::setenv(nbuf, vbuf, 1);
                    })
410 411
                })
            })
A
Axel Viala 已提交
412
        }
413
    }
414

A
Axel Viala 已提交
415
    #[cfg(windows)]
416
    fn _setenv(n: &str, v: &[u8]) {
J
John Schmidt 已提交
417 418
        let n: Vec<u16> = n.utf16_units().collect();
        let n = n.append_one(0);
419
        let v: Vec<u16> = str::from_utf8(v).unwrap().utf16_units().collect();
J
John Schmidt 已提交
420
        let v = v.append_one(0);
421

A
Axel Viala 已提交
422 423 424 425 426
        unsafe {
            with_env_lock(|| {
                libc::SetEnvironmentVariableW(n.as_ptr(), v.as_ptr());
            })
        }
427
    }
428 429

    _setenv(n, v.container_as_bytes())
430 431
}

A
Axel Viala 已提交
432
/// Remove a variable from the environment entirely.
C
Corey Richardson 已提交
433 434 435 436
pub fn unsetenv(n: &str) {
    #[cfg(unix)]
    fn _unsetenv(n: &str) {
        unsafe {
437 438
            with_env_lock(|| {
                n.with_c_str(|nbuf| {
C
Corey Richardson 已提交
439
                    libc::funcs::posix01::unistd::unsetenv(nbuf);
440 441
                })
            })
C
Corey Richardson 已提交
442 443
        }
    }
A
Axel Viala 已提交
444

C
Corey Richardson 已提交
445 446
    #[cfg(windows)]
    fn _unsetenv(n: &str) {
J
John Schmidt 已提交
447 448
        let n: Vec<u16> = n.utf16_units().collect();
        let n = n.append_one(0);
C
Corey Richardson 已提交
449
        unsafe {
450
            with_env_lock(|| {
451
                libc::SetEnvironmentVariableW(n.as_ptr(), ptr::null());
452
            })
C
Corey Richardson 已提交
453 454 455 456 457
        }
    }
    _unsetenv(n);
}

458 459
/// Parses input according to platform conventions for the `PATH`
/// environment variable.
A
Axel Viala 已提交
460 461 462 463 464 465
///
/// # Example
/// ```rust
/// use std::os;
///
/// let key = "PATH";
466
/// match os::getenv_as_bytes(key) {
A
Axel Viala 已提交
467 468 469 470 471
///     Some(paths) => {
///         for path in os::split_paths(paths).iter() {
///             println!("'{}'", path.display());
///         }
///     }
J
Joseph Crail 已提交
472
///     None => println!("{} is not defined in the environment.", key)
A
Axel Viala 已提交
473 474
/// }
/// ```
A
Aaron Turon 已提交
475
pub fn split_paths<T: BytesContainer>(unparsed: T) -> Vec<Path> {
476 477 478 479 480 481 482
    #[cfg(unix)]
    fn _split_paths<T: BytesContainer>(unparsed: T) -> Vec<Path> {
        unparsed.container_as_bytes()
                .split(|b| *b == b':')
                .map(Path::new)
                .collect()
    }
A
Aaron Turon 已提交
483

484
    #[cfg(windows)]
A
Alex Crichton 已提交
485
    fn _split_paths<T: BytesContainer>(unparsed: T) -> Vec<Path> {
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
        // On Windows, the PATH environment variable is semicolon separated.  Double
        // quotes are used as a way of introducing literal semicolons (since
        // c:\some;dir is a valid Windows path). Double quotes are not themselves
        // permitted in path names, so there is no way to escape a double quote.
        // Quoted regions can appear in arbitrary locations, so
        //
        //   c:\foo;c:\som"e;di"r;c:\bar
        //
        // Should parse as [c:\foo, c:\some;dir, c:\bar].
        //
        // (The above is based on testing; there is no clear reference available
        // for the grammar.)

        let mut parsed = Vec::new();
        let mut in_progress = Vec::new();
        let mut in_quote = false;

        for b in unparsed.container_as_bytes().iter() {
            match *b {
                b';' if !in_quote => {
A
Aaron Turon 已提交
506
                    parsed.push(Path::new(in_progress.as_slice()));
507 508 509 510 511 512 513
                    in_progress.truncate(0)
                }
                b'"' => {
                    in_quote = !in_quote;
                }
                _  => {
                    in_progress.push(*b);
A
Aaron Turon 已提交
514 515
                }
            }
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560
        }
        parsed.push(Path::new(in_progress));
        parsed
    }

    _split_paths(unparsed)
}

/// Joins a collection of `Path`s appropriately for the `PATH`
/// environment variable.
///
/// Returns a `Vec<u8>` on success, since `Path`s are not utf-8
/// encoded on all platforms.
///
/// Returns an `Err` (containing an error message) if one of the input
/// `Path`s contains an invalid character for constructing the `PATH`
/// variable (a double quote on Windows or a colon on Unix).
///
/// # Example
///
/// ```rust
/// use std::os;
/// use std::path::Path;
///
/// let key = "PATH";
/// let mut paths = os::getenv_as_bytes(key).map_or(Vec::new(), os::split_paths);
/// paths.push(Path::new("/home/xyz/bin"));
/// os::setenv(key, os::join_paths(paths.as_slice()).unwrap());
/// ```
pub fn join_paths<T: BytesContainer>(paths: &[T]) -> Result<Vec<u8>, &'static str> {
    #[cfg(windows)]
    fn _join_paths<T: BytesContainer>(paths: &[T]) -> Result<Vec<u8>, &'static str> {
        let mut joined = Vec::new();
        let sep = b';';

        for (i, path) in paths.iter().map(|p| p.container_as_bytes()).enumerate() {
            if i > 0 { joined.push(sep) }
            if path.contains(&b'"') {
                return Err("path segment contains `\"`");
            } else if path.contains(&sep) {
                joined.push(b'"');
                joined.push_all(path);
                joined.push(b'"');
            } else {
                joined.push_all(path);
A
Aaron Turon 已提交
561 562
            }
        }
563 564

        Ok(joined)
A
Aaron Turon 已提交
565 566
    }

567 568 569 570 571 572 573 574 575 576 577 578
    #[cfg(unix)]
    fn _join_paths<T: BytesContainer>(paths: &[T]) -> Result<Vec<u8>, &'static str> {
        let mut joined = Vec::new();
        let sep = b':';

        for (i, path) in paths.iter().map(|p| p.container_as_bytes()).enumerate() {
            if i > 0 { joined.push(sep) }
            if path.contains(&sep) { return Err("path segment contains separator `:`") }
            joined.push_all(path);
        }

        Ok(joined)
A
Aaron Turon 已提交
579 580
    }

581
    _join_paths(paths)
A
Aaron Turon 已提交
582 583
}

584
/// A low-level OS in-memory pipe.
585
pub struct Pipe {
586 587
    /// A file descriptor representing the reading end of the pipe. Data written
    /// on the `out` file descriptor can be read from this file descriptor.
588
    pub reader: c_int,
589 590
    /// A file descriptor representing the write end of the pipe. Data written
    /// to this file descriptor can be read from the `input` file descriptor.
591
    pub writer: c_int,
592
}
593

594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
/// Creates a new low-level OS in-memory pipe.
///
/// This function can fail to succeed if there are no more resources available
/// to allocate a pipe.
///
/// This function is also unsafe as there is no destructor associated with the
/// `Pipe` structure will return. If it is not arranged for the returned file
/// descriptors to be closed, the file descriptors will leak. For safe handling
/// of this scenario, use `std::io::PipeStream` instead.
pub unsafe fn pipe() -> IoResult<Pipe> {
    return _pipe();

    #[cfg(unix)]
    unsafe fn _pipe() -> IoResult<Pipe> {
        let mut fds = [0, ..2];
        match libc::pipe(fds.as_mut_ptr()) {
            0 => Ok(Pipe { reader: fds[0], writer: fds[1] }),
            _ => Err(IoError::last_error()),
        }
613
    }
614

615 616
    #[cfg(windows)]
    unsafe fn _pipe() -> IoResult<Pipe> {
617 618 619 620
        // Windows pipes work subtly differently than unix pipes, and their
        // inheritance has to be handled in a different way that I do not
        // fully understand. Here we explicitly make the pipe non-inheritable,
        // which means to pass it to a subprocess they need to be duplicated
621
        // first, as in std::run.
622 623 624 625 626 627 628 629 630 631
        let mut fds = [0, ..2];
        match libc::pipe(fds.as_mut_ptr(), 1024 as ::libc::c_uint,
                         (libc::O_BINARY | libc::O_NOINHERIT) as c_int) {
            0 => {
                assert!(fds[0] != -1 && fds[0] != 0);
                assert!(fds[1] != -1 && fds[1] != 0);
                Ok(Pipe { reader: fds[0], writer: fds[1] })
            }
            _ => Err(IoError::last_error()),
        }
632
    }
633 634
}

A
Axel Viala 已提交
635 636
/// Returns the proper dll filename for the given basename of a file
/// as a String.
V
Valerii Hiora 已提交
637
#[cfg(not(target_os="ios"))]
638
pub fn dll_filename(base: &str) -> String {
A
Alex Crichton 已提交
639
    format!("{}{}{}", consts::DLL_PREFIX, base, consts::DLL_SUFFIX)
640 641
}

A
Axel Viala 已提交
642 643 644 645 646 647 648 649 650 651 652 653 654
/// Optionally returns the filesystem path to the current executable which is
/// running but with the executable name.
///
/// # Examples
///
/// ```rust
/// use std::os;
///
/// match os::self_exe_name() {
///     Some(exe_path) => println!("Path of this executable is: {}", exe_path.display()),
///     None => println!("Unable to get the path of this executable!")
/// };
/// ```
B
Ben Noordhuis 已提交
655
pub fn self_exe_name() -> Option<Path> {
656 657

    #[cfg(target_os = "freebsd")]
K
Kevin Ballard 已提交
658
    fn load_self() -> Option<Vec<u8>> {
659
        unsafe {
660 661
            use libc::funcs::bsd44::*;
            use libc::consts::os::extra::*;
662 663 664 665
            let mut mib = vec![CTL_KERN as c_int,
                               KERN_PROC as c_int,
                               KERN_PROC_PATHNAME as c_int,
                               -1 as c_int];
A
Alex Crichton 已提交
666
            let mut sz: libc::size_t = 0;
667 668
            let err = sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint,
                             ptr::mut_null(), &mut sz, ptr::mut_null(),
A
Alex Crichton 已提交
669
                             0u as libc::size_t);
670 671
            if err != 0 { return None; }
            if sz == 0 { return None; }
A
Alex Crichton 已提交
672
            let mut v: Vec<u8> = Vec::with_capacity(sz as uint);
673 674 675
            let err = sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint,
                             v.as_mut_ptr() as *mut c_void, &mut sz,
                             ptr::mut_null(), 0u as libc::size_t);
676 677
            if err != 0 { return None; }
            if sz == 0 { return None; }
678
            v.set_len(sz as uint - 1); // chop off trailing NUL
K
Kevin Ballard 已提交
679
            Some(v)
680
        }
681 682 683
    }

    #[cfg(target_os = "linux")]
K
kyeongwoon 已提交
684
    #[cfg(target_os = "android")]
K
Kevin Ballard 已提交
685
    fn load_self() -> Option<Vec<u8>> {
A
Alex Crichton 已提交
686
        use std::io;
687

A
Alex Crichton 已提交
688
        match io::fs::readlink(&Path::new("/proc/self/exe")) {
K
Kevin Ballard 已提交
689
            Ok(path) => Some(path.into_vec()),
A
Alex Crichton 已提交
690
            Err(..) => None
691 692 693
        }
    }

694
    #[cfg(target_os = "macos")]
V
Valerii Hiora 已提交
695
    #[cfg(target_os = "ios")]
K
Kevin Ballard 已提交
696
    fn load_self() -> Option<Vec<u8>> {
697
        unsafe {
698 699 700 701
            use libc::funcs::extra::_NSGetExecutablePath;
            let mut sz: u32 = 0;
            _NSGetExecutablePath(ptr::mut_null(), &mut sz);
            if sz == 0 { return None; }
702
            let mut v: Vec<u8> = Vec::with_capacity(sz as uint);
703
            let err = _NSGetExecutablePath(v.as_mut_ptr() as *mut i8, &mut sz);
704
            if err != 0 { return None; }
705
            v.set_len(sz as uint - 1); // chop off trailing NUL
K
Kevin Ballard 已提交
706
            Some(v)
707
        }
708 709
    }

710
    #[cfg(windows)]
K
Kevin Ballard 已提交
711
    fn load_self() -> Option<Vec<u8>> {
712 713
        use str::OwnedStr;

714 715
        unsafe {
            use os::win32::fill_utf16_buf_and_decode;
716
            fill_utf16_buf_and_decode(|buf, sz| {
717
                libc::GetModuleFileNameW(0u as libc::DWORD, buf, sz)
718
            }).map(|s| s.into_string().into_bytes())
719
        }
720 721
    }

B
Ben Noordhuis 已提交
722 723 724 725
    load_self().and_then(Path::new_opt)
}

/// Optionally returns the filesystem path to the current executable which is
A
Axel Viala 已提交
726 727 728 729 730 731 732 733 734 735 736 737 738 739
/// running.
///
/// Like self_exe_name() but without the binary's name.
///
/// # Example
///
/// ```rust
/// use std::os;
///
/// match os::self_exe_path() {
///     Some(exe_path) => println!("Executable's Path is: {}", exe_path.display()),
///     None => println!("Impossible to fetch the path of this executable.")
/// };
/// ```
B
Ben Noordhuis 已提交
740 741
pub fn self_exe_path() -> Option<Path> {
    self_exe_name().map(|mut p| { p.pop(); p })
742 743
}

A
Axel Viala 已提交
744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767
/// Optionally returns the path to the current user's home directory if known.
///
/// # Unix
///
/// Returns the value of the 'HOME' environment variable if it is set
/// and not equal to the empty string.
///
/// # Windows
///
/// Returns the value of the 'HOME' environment variable if it is
/// set and not equal to the empty string. Otherwise, returns the value of the
/// 'USERPROFILE' environment variable if it is set and not equal to the empty
/// string.
///
/// # Example
///
/// ```rust
/// use std::os;
///
/// match os::homedir() {
///     Some(ref p) => println!("{}", p.display()),
///     None => println!("Impossible to get your home dir!")
/// }
/// ```
768
pub fn homedir() -> Option<Path> {
A
Axel Viala 已提交
769
    #[inline]
770
    #[cfg(unix)]
A
Axel Viala 已提交
771 772
    fn _homedir() -> Option<Path> {
        aux_homedir("HOME")
773 774
    }

A
Axel Viala 已提交
775
    #[inline]
776
    #[cfg(windows)]
A
Axel Viala 已提交
777 778 779 780 781 782 783 784 785 786 787 788
    fn _homedir() -> Option<Path> {
        aux_homedir("HOME").or(aux_homedir("USERPROFILE"))
    }

    #[inline]
    fn aux_homedir(home_name: &str) -> Option<Path> {
        match getenv_as_bytes(home_name) {
            Some(p)  => {
                if p.is_empty() { None } else { Path::new_opt(p) }
            },
            _ => None
        }
789
    }
A
Axel Viala 已提交
790
    _homedir()
791 792
}

793
/**
794
 * Returns the path to a temporary directory.
795 796
 *
 * On Unix, returns the value of the 'TMPDIR' environment variable if it is
797 798 799
 * set, otherwise for non-Android it returns '/tmp'. If Android, since there
 * is no global temporary folder (it is usually allocated per-app), we return
 * '/data/local/tmp'.
800 801
 *
 * On Windows, returns the value of, in order, the 'TMP', 'TEMP',
802 803
 * 'USERPROFILE' environment variable  if any are set and not the empty
 * string. Otherwise, tmpdir returns the path to the Windows directory.
804
 */
805
pub fn tmpdir() -> Path {
806 807
    return lookup();

B
Brian Anderson 已提交
808
    fn getenv_nonempty(v: &str) -> Option<Path> {
809
        match getenv(v) {
L
Luqman Aden 已提交
810
            Some(x) =>
811
                if x.is_empty() {
B
Brian Anderson 已提交
812
                    None
813
                } else {
814
                    Path::new_opt(x)
815
                },
B
Brian Anderson 已提交
816
            _ => None
817 818 819 820
        }
    }

    #[cfg(unix)]
821
    fn lookup() -> Path {
822 823
        let default = if cfg!(target_os = "android") {
            Path::new("/data/local/tmp")
824
        } else {
825 826 827 828
            Path::new("/tmp")
        };

        getenv_nonempty("TMPDIR").unwrap_or(default)
829 830 831
    }

    #[cfg(windows)]
832
    fn lookup() -> Path {
833 834 835
        getenv_nonempty("TMP").or(
            getenv_nonempty("TEMP").or(
                getenv_nonempty("USERPROFILE").or(
836
                   getenv_nonempty("WINDIR")))).unwrap_or(Path::new("C:\\Windows"))
837 838
    }
}
B
Brian Anderson 已提交
839

A
Anton Lofgren 已提交
840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857
///
/// Convert a relative path to an absolute path
///
/// If the given path is relative, return it prepended with the current working
/// directory. If the given path is already an absolute path, return it
/// as is.
///
/// # Example
/// ```rust
/// use std::os;
/// use std::path::Path;
///
/// // Assume we're in a path like /home/someuser
/// let rel_path = Path::new("..");
/// let abs_path = os::make_absolute(&rel_path);
/// println!("The absolute path is {}", abs_path.display());
/// // Prints "The absolute path is /home"
/// ```
858 859 860
// NB: this is here rather than in path because it is a form of environment
// querying; what it does depends on the process working directory, not just
// the input paths.
861
pub fn make_absolute(p: &Path) -> Path {
862 863
    if p.is_absolute() {
        p.clone()
864
    } else {
865
        let mut ret = getcwd();
866
        ret.push(p);
867
        ret
868
    }
869 870
}

871 872
/// Changes the current working directory to the specified path, returning
/// whether the change was completed successfully or not.
A
Anton Lofgren 已提交
873 874 875 876 877 878 879 880 881 882
///
/// # Example
/// ```rust
/// use std::os;
/// use std::path::Path;
///
/// let root = Path::new("/");
/// assert!(os::change_dir(&root));
/// println!("Succesfully changed working directory to {}!", root.display());
/// ```
883
pub fn change_dir(p: &Path) -> bool {
B
Brian Anderson 已提交
884
    return chdir(p);
885

886
    #[cfg(windows)]
887
    fn chdir(p: &Path) -> bool {
888
        let p = match p.as_str() {
J
John Schmidt 已提交
889
            Some(s) => s.utf16_units().collect::<Vec<u16>>().append_one(0),
890 891
            None => return false,
        };
892
        unsafe {
893
            libc::SetCurrentDirectoryW(p.as_ptr()) != (0 as libc::BOOL)
894
        }
895 896
    }

897
    #[cfg(unix)]
898
    fn chdir(p: &Path) -> bool {
899
        p.with_c_str(|buf| {
E
Erick Tryzelaar 已提交
900
            unsafe {
901
                libc::chdir(buf) == (0 as c_int)
E
Erick Tryzelaar 已提交
902
            }
903
        })
904 905 906
    }
}

907
#[cfg(unix)]
908
/// Returns the platform-specific value of errno
909 910
pub fn errno() -> int {
    #[cfg(target_os = "macos")]
V
Valerii Hiora 已提交
911
    #[cfg(target_os = "ios")]
912
    #[cfg(target_os = "freebsd")]
913
    fn errno_location() -> *const c_int {
914
        extern {
915
            fn __error() -> *const c_int;
916 917 918 919 920 921 922 923
        }
        unsafe {
            __error()
        }
    }

    #[cfg(target_os = "linux")]
    #[cfg(target_os = "android")]
924
    fn errno_location() -> *const c_int {
925
        extern {
926
            fn __errno_location() -> *const c_int;
927 928 929 930 931 932 933 934 935 936 937 938
        }
        unsafe {
            __errno_location()
        }
    }

    unsafe {
        (*errno_location()) as int
    }
}

#[cfg(windows)]
939
/// Returns the platform-specific value of errno
940 941 942 943
pub fn errno() -> uint {
    use libc::types::os::arch::extra::DWORD;

    #[link_name = "kernel32"]
A
Alex Crichton 已提交
944
    extern "system" {
K
klutzy 已提交
945 946 947
        fn GetLastError() -> DWORD;
    }

948
    unsafe {
949
        GetLastError() as uint
950 951 952
    }
}

953
/// Return the string corresponding to an `errno()` value of `errnum`.
A
Anton Lofgren 已提交
954 955 956 957 958 959 960
/// # Example
/// ```rust
/// use std::os;
///
/// // Same as println!("{}", last_os_error());
/// println!("{}", os::error_string(os::errno() as uint));
/// ```
961
pub fn error_string(errnum: uint) -> String {
962 963
    return strerror(errnum);

964
    #[cfg(unix)]
965
    fn strerror(errnum: uint) -> String {
966
        #[cfg(target_os = "macos")]
V
Valerii Hiora 已提交
967
        #[cfg(target_os = "ios")]
968 969
        #[cfg(target_os = "android")]
        #[cfg(target_os = "freebsd")]
A
Alex Crichton 已提交
970
        fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: libc::size_t)
971
                      -> c_int {
972
            extern {
A
Alex Crichton 已提交
973 974
                fn strerror_r(errnum: c_int, buf: *mut c_char,
                              buflen: libc::size_t) -> c_int;
975 976 977 978 979 980 981 982
            }
            unsafe {
                strerror_r(errnum, buf, buflen)
            }
        }

        // GNU libc provides a non-compliant version of strerror_r by default
        // and requires macros to instead use the POSIX compliant variant.
L
Luqman Aden 已提交
983
        // So we just use __xpg_strerror_r which is always POSIX compliant
984
        #[cfg(target_os = "linux")]
A
Alex Crichton 已提交
985 986
        fn strerror_r(errnum: c_int, buf: *mut c_char,
                      buflen: libc::size_t) -> c_int {
987
            extern {
988 989
                fn __xpg_strerror_r(errnum: c_int,
                                    buf: *mut c_char,
A
Alex Crichton 已提交
990
                                    buflen: libc::size_t)
991
                                    -> c_int;
992 993 994 995 996 997 998
            }
            unsafe {
                __xpg_strerror_r(errnum, buf, buflen)
            }
        }

        let mut buf = [0 as c_char, ..TMPBUF_SZ];
999

1000 1001
        let p = buf.as_mut_ptr();
        unsafe {
1002
            if strerror_r(errnum as c_int, p, buf.len() as libc::size_t) < 0 {
1003
                fail!("strerror_r failure");
1004
            }
1005

1006
            str::raw::from_c_str(p as *const c_char).into_string()
1007
        }
1008
    }
1009 1010

    #[cfg(windows)]
1011
    fn strerror(errnum: uint) -> String {
1012
        use libc::types::os::arch::extra::DWORD;
1013
        use libc::types::os::arch::extra::LPWSTR;
1014
        use libc::types::os::arch::extra::LPVOID;
1015
        use libc::types::os::arch::extra::WCHAR;
1016 1017

        #[link_name = "kernel32"]
A
Alex Crichton 已提交
1018
        extern "system" {
1019
            fn FormatMessageW(flags: DWORD,
K
klutzy 已提交
1020 1021 1022
                              lpSrc: LPVOID,
                              msgId: DWORD,
                              langId: DWORD,
1023
                              buf: LPWSTR,
K
klutzy 已提交
1024
                              nsize: DWORD,
1025
                              args: *const c_void)
K
klutzy 已提交
1026 1027 1028
                              -> DWORD;
        }

1029 1030
        static FORMAT_MESSAGE_FROM_SYSTEM: DWORD = 0x00001000;
        static FORMAT_MESSAGE_IGNORE_INSERTS: DWORD = 0x00000200;
1031 1032 1033 1034 1035

        // This value is calculated from the macro
        // MAKELANGID(LANG_SYSTEM_DEFAULT, SUBLANG_SYS_DEFAULT)
        let langId = 0x0800 as DWORD;

1036
        let mut buf = [0 as WCHAR, ..TMPBUF_SZ];
1037

1038
        unsafe {
1039 1040 1041
            let res = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
                                     FORMAT_MESSAGE_IGNORE_INSERTS,
                                     ptr::mut_null(),
1042
                                     errnum as DWORD,
1043 1044 1045 1046 1047
                                     langId,
                                     buf.as_mut_ptr(),
                                     buf.len() as DWORD,
                                     ptr::null());
            if res == 0 {
K
klutzy 已提交
1048 1049
                // Sometimes FormatMessageW can fail e.g. system doesn't like langId,
                let fm_err = errno();
1050
                return format!("OS Error {} (FormatMessageW() returned error {})", errnum, fm_err);
1051
            }
1052

A
Adolfo Ochagavía 已提交
1053
            let msg = String::from_utf16(str::truncate_utf16_at_nul(buf));
K
klutzy 已提交
1054
            match msg {
1055 1056
                Some(msg) => format!("OS Error {}: {}", errnum, msg),
                None => format!("OS Error {} (FormatMessageW() returned invalid UTF-16)", errnum),
K
klutzy 已提交
1057
            }
1058 1059
        }
    }
1060
}
1061

1062
/// Get a string representing the platform-dependent last error
1063
pub fn last_os_error() -> String {
1064
    error_string(errno() as uint)
1065
}
1066

1067 1068
static mut EXIT_STATUS: AtomicInt = INIT_ATOMIC_INT;

1069 1070 1071 1072 1073 1074
/**
 * Sets the process exit code
 *
 * Sets the exit code returned by the process if all supervised tasks
 * terminate successfully (without failing). If the current root task fails
 * and is supervised by the scheduler then any user-specified exit status is
1075 1076 1077
 * ignored and the process exits with the default failure status.
 *
 * Note that this is not synchronized against modifications of other threads.
1078
 */
1079
pub fn set_exit_status(code: int) {
1080 1081 1082 1083 1084 1085 1086
    unsafe { EXIT_STATUS.store(code, SeqCst) }
}

/// Fetches the process's current exit code. This defaults to 0 and can change
/// by calling `set_exit_status`.
pub fn get_exit_status() -> int {
    unsafe { EXIT_STATUS.load(SeqCst) }
1087
}
1088

K
Kiet Tran 已提交
1089
#[cfg(target_os = "macos")]
1090 1091
unsafe fn load_argc_and_argv(argc: int,
                             argv: *const *const c_char) -> Vec<Vec<u8>> {
1092 1093
    use c_str::CString;

1094
    Vec::from_fn(argc as uint, |i| {
1095 1096
        Vec::from_slice(CString::new(*argv.offset(i as int),
                                     false).as_bytes_no_nul())
K
Kevin Ballard 已提交
1097
    })
1098 1099
}

1100 1101 1102 1103 1104 1105
/**
 * Returns the command line arguments
 *
 * Returns a list of the command line arguments.
 */
#[cfg(target_os = "macos")]
1106
fn real_args_as_bytes() -> Vec<Vec<u8>> {
1107
    unsafe {
1108
        let (argc, argv) = (*_NSGetArgc() as int,
1109
                            *_NSGetArgv() as *const *const c_char);
1110
        load_argc_and_argv(argc, argv)
1111 1112 1113
    }
}

V
Valerii Hiora 已提交
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
// As _NSGetArgc and _NSGetArgv aren't mentioned in iOS docs
// and use underscores in their names - they're most probably
// are considered private and therefore should be avoided
// Here is another way to get arguments using Objective C
// runtime
//
// In general it looks like:
// res = Vec::new()
// let args = [[NSProcessInfo processInfo] arguments]
// for i in range(0, [args count])
//      res.push([args objectAtIndex:i])
// res
#[cfg(target_os = "ios")]
fn real_args_as_bytes() -> Vec<Vec<u8>> {
    use c_str::CString;
    use iter::range;
    use mem;

    #[link(name = "objc")]
    extern {
1134
        fn sel_registerName(name: *const libc::c_uchar) -> Sel;
V
Valerii Hiora 已提交
1135
        fn objc_msgSend(obj: NsId, sel: Sel, ...) -> NsId;
1136
        fn objc_getClass(class_name: *const libc::c_uchar) -> NsId;
V
Valerii Hiora 已提交
1137 1138 1139 1140 1141
    }

    #[link(name = "Foundation", kind = "framework")]
    extern {}

1142 1143
    type Sel = *const libc::c_void;
    type NsId = *const libc::c_void;
V
Valerii Hiora 已提交
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160

    let mut res = Vec::new();

    unsafe {
        let processInfoSel = sel_registerName("processInfo\0".as_ptr());
        let argumentsSel = sel_registerName("arguments\0".as_ptr());
        let utf8Sel = sel_registerName("UTF8String\0".as_ptr());
        let countSel = sel_registerName("count\0".as_ptr());
        let objectAtSel = sel_registerName("objectAtIndex:\0".as_ptr());

        let klass = objc_getClass("NSProcessInfo\0".as_ptr());
        let info = objc_msgSend(klass, processInfoSel);
        let args = objc_msgSend(info, argumentsSel);

        let cnt: int = mem::transmute(objc_msgSend(args, countSel));
        for i in range(0, cnt) {
            let tmp = objc_msgSend(args, objectAtSel, i);
1161 1162
            let utf_c_str: *const libc::c_char =
                mem::transmute(objc_msgSend(tmp, utf8Sel));
V
Valerii Hiora 已提交
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
            let s = CString::new(utf_c_str, false);
            if s.is_not_null() {
                res.push(Vec::from_slice(s.as_bytes_no_nul()))
            }
        }
    }

    res
}

1173
#[cfg(target_os = "linux")]
K
kyeongwoon 已提交
1174
#[cfg(target_os = "android")]
1175
#[cfg(target_os = "freebsd")]
1176
fn real_args_as_bytes() -> Vec<Vec<u8>> {
1177 1178
    use rt;

1179 1180
    match rt::args::clone() {
        Some(args) => args,
1181
        None => fail!("process arguments not initialized")
1182
    }
1183 1184
}

1185
#[cfg(not(windows))]
1186
fn real_args() -> Vec<String> {
1187
    real_args_as_bytes().move_iter()
1188
                        .map(|v| {
1189
                            str::from_utf8_lossy(v.as_slice()).into_string()
1190
                        }).collect()
1191 1192
}

1193
#[cfg(windows)]
1194
fn real_args() -> Vec<String> {
D
Daniel Micay 已提交
1195
    use slice;
1196

1197
    let mut nArgs: c_int = 0;
D
Daniel Micay 已提交
1198
    let lpArgCount: *mut c_int = &mut nArgs;
T
Tim Chevalier 已提交
1199 1200
    let lpCmdLine = unsafe { GetCommandLineW() };
    let szArgList = unsafe { CommandLineToArgvW(lpCmdLine, lpArgCount) };
1201

1202 1203 1204 1205 1206 1207 1208
    let args = Vec::from_fn(nArgs as uint, |i| unsafe {
        // Determine the length of this argument.
        let ptr = *szArgList.offset(i as int);
        let mut len = 0;
        while *ptr.offset(len as int) != 0 { len += 1; }

        // Push it onto the list.
1209
        let opt_s = slice::raw::buf_as_slice(ptr as *const _, len, |buf| {
A
Adolfo Ochagavía 已提交
1210
            String::from_utf16(str::truncate_utf16_at_nul(buf))
1211 1212 1213
        });
        opt_s.expect("CommandLineToArgvW returned invalid UTF-16")
    });
1214 1215

    unsafe {
1216
        LocalFree(szArgList as *mut c_void);
1217 1218
    }

K
Kevin Ballard 已提交
1219
    return args
1220 1221
}

1222
#[cfg(windows)]
1223
fn real_args_as_bytes() -> Vec<Vec<u8>> {
1224 1225 1226
    real_args().move_iter().map(|s| s.into_bytes()).collect()
}

1227
type LPCWSTR = *const u16;
1228

A
Alex Crichton 已提交
1229
#[cfg(windows)]
K
klutzy 已提交
1230
#[link_name="kernel32"]
A
Alex Crichton 已提交
1231
extern "system" {
K
klutzy 已提交
1232
    fn GetCommandLineW() -> LPCWSTR;
1233
    fn LocalFree(ptr: *mut c_void);
K
klutzy 已提交
1234 1235
}

A
Alex Crichton 已提交
1236
#[cfg(windows)]
K
klutzy 已提交
1237
#[link_name="shell32"]
A
Alex Crichton 已提交
1238
extern "system" {
1239 1240
    fn CommandLineToArgvW(lpCmdLine: LPCWSTR,
                          pNumArgs: *mut c_int) -> *mut *mut u16;
K
klutzy 已提交
1241 1242
}

1243 1244
/// Returns the arguments which this program was started with (normally passed
/// via the command line).
1245 1246 1247
///
/// The arguments are interpreted as utf-8, with invalid bytes replaced with \uFFFD.
/// See `str::from_utf8_lossy` for details.
A
Anton Lofgren 已提交
1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
/// # Example
///
/// ```rust
/// use std::os;
///
/// // Prints each argument on a separate line
/// for argument in os::args().iter() {
///     println!("{}", argument);
/// }
/// ```
1258
pub fn args() -> Vec<String> {
1259
    real_args()
1260 1261
}

1262 1263
/// Returns the arguments which this program was started with (normally passed
/// via the command line) as byte vectors.
1264
pub fn args_as_bytes() -> Vec<Vec<u8>> {
1265 1266 1267
    real_args_as_bytes()
}

1268 1269 1270
#[cfg(target_os = "macos")]
extern {
    // These functions are in crt_externs.h.
1271 1272
    pub fn _NSGetArgc() -> *mut c_int;
    pub fn _NSGetArgv() -> *mut *mut *mut c_char;
1273 1274
}

1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288
// Round up `from` to be divisible by `to`
fn round_up(from: uint, to: uint) -> uint {
    let r = if from % to == 0 {
        from
    } else {
        from + to - (from % to)
    };
    if r == 0 {
        to
    } else {
        r
    }
}

1289
/// Returns the page size of the current architecture in bytes.
1290 1291 1292 1293 1294 1295 1296
#[cfg(unix)]
pub fn page_size() -> uint {
    unsafe {
        libc::sysconf(libc::_SC_PAGESIZE) as uint
    }
}

1297
/// Returns the page size of the current architecture in bytes.
1298 1299
#[cfg(windows)]
pub fn page_size() -> uint {
1300
    use mem;
V
Vadim Chugunov 已提交
1301
    unsafe {
1302
        let mut info = mem::zeroed();
V
Vadim Chugunov 已提交
1303
        libc::GetSystemInfo(&mut info);
1304

V
Vadim Chugunov 已提交
1305 1306
        return info.dwPageSize as uint;
    }
1307 1308
}

A
Alex Crichton 已提交
1309 1310 1311 1312
/// A memory mapped file or chunk of memory. This is a very system-specific
/// interface to the OS's memory mapping facilities (`mmap` on POSIX,
/// `VirtualAlloc`/`CreateFileMapping` on win32). It makes no attempt at
/// abstracting platform differences, besides in error values returned. Consider
C
Corey Richardson 已提交
1313 1314
/// yourself warned.
///
A
Alex Crichton 已提交
1315 1316
/// The memory map is released (unmapped) when the destructor is run, so don't
/// let it leave scope by accident if you want it to stick around.
1317
pub struct MemoryMap {
1318 1319 1320
    data: *mut u8,
    len: uint,
    kind: MemoryMapKind,
1321 1322
}

C
Corey Richardson 已提交
1323
/// Type of memory map
1324
pub enum MemoryMapKind {
A
Alex Crichton 已提交
1325 1326
    /// Virtual memory map. Usually used to change the permissions of a given
    /// chunk of memory.  Corresponds to `VirtualAlloc` on Windows.
1327
    MapFile(*const u8),
A
Alex Crichton 已提交
1328 1329 1330
    /// Virtual memory map. Usually used to change the permissions of a given
    /// chunk of memory, or for allocation. Corresponds to `VirtualAlloc` on
    /// Windows.
1331 1332 1333
    MapVirtual
}

C
Corey Richardson 已提交
1334
/// Options the memory map is created with
1335
pub enum MapOption {
C
Corey Richardson 已提交
1336
    /// The memory should be readable
1337
    MapReadable,
C
Corey Richardson 已提交
1338
    /// The memory should be writable
1339
    MapWritable,
C
Corey Richardson 已提交
1340
    /// The memory should be executable
1341
    MapExecutable,
A
Alex Crichton 已提交
1342 1343
    /// Create a map for a specific address range. Corresponds to `MAP_FIXED` on
    /// POSIX.
1344
    MapAddr(*const u8),
C
Corey Richardson 已提交
1345
    /// Create a memory mapping for a file with a given fd.
1346
    MapFd(c_int),
A
Alex Crichton 已提交
1347 1348
    /// When using `MapFd`, the start of the map is `uint` bytes from the start
    /// of the file.
1349
    MapOffset(uint),
A
Alex Crichton 已提交
1350 1351 1352 1353
    /// On POSIX, this can be used to specify the default flags passed to
    /// `mmap`. By default it uses `MAP_PRIVATE` and, if not using `MapFd`,
    /// `MAP_ANON`. This will override both of those. This is platform-specific
    /// (the exact values used) and ignored on Windows.
1354
    MapNonStandardFlags(c_int),
1355 1356
}

C
Corey Richardson 已提交
1357
/// Possible errors when creating a map.
1358
pub enum MapError {
C
Corey Richardson 已提交
1359 1360
    /// ## The following are POSIX-specific
    ///
A
Alex Crichton 已提交
1361 1362
    /// fd was not open for reading or, if using `MapWritable`, was not open for
    /// writing.
1363
    ErrFdNotAvail,
C
Corey Richardson 已提交
1364
    /// fd was not valid
1365
    ErrInvalidFd,
A
Alex Crichton 已提交
1366 1367
    /// Either the address given by `MapAddr` or offset given by `MapOffset` was
    /// not a multiple of `MemoryMap::granularity` (unaligned to page size).
1368
    ErrUnaligned,
C
Corey Richardson 已提交
1369
    /// With `MapFd`, the fd does not support mapping.
1370
    ErrNoMapSupport,
A
Alex Crichton 已提交
1371 1372 1373
    /// If using `MapAddr`, the address + `min_len` was outside of the process's
    /// address space. If using `MapFd`, the target of the fd didn't have enough
    /// resources to fulfill the request.
1374
    ErrNoMem,
C
Corey Richardson 已提交
1375
    /// A zero-length map was requested. This is invalid according to
A
Alex Crichton 已提交
1376 1377
    /// [POSIX](http://pubs.opengroup.org/onlinepubs/9699919799/functions/mmap.html).
    /// Not all platforms obey this, but this wrapper does.
C
Corey Richardson 已提交
1378
    ErrZeroLength,
C
Corey Richardson 已提交
1379
    /// Unrecognized error. The inner value is the unrecognized errno.
1380
    ErrUnknown(int),
C
Corey Richardson 已提交
1381 1382
    /// ## The following are win32-specific
    ///
A
Alex Crichton 已提交
1383 1384
    /// Unsupported combination of protection flags
    /// (`MapReadable`/`MapWritable`/`MapExecutable`).
1385
    ErrUnsupProt,
A
Alex Crichton 已提交
1386 1387
    /// When using `MapFd`, `MapOffset` was given (Windows does not support this
    /// at all)
1388
    ErrUnsupOffset,
C
Corey Richardson 已提交
1389
    /// When using `MapFd`, there was already a mapping to the file.
1390
    ErrAlreadyExists,
A
Alex Crichton 已提交
1391 1392
    /// Unrecognized error from `VirtualAlloc`. The inner value is the return
    /// value of GetLastError.
1393
    ErrVirtualAlloc(uint),
A
Alex Crichton 已提交
1394 1395
    /// Unrecognized error from `CreateFileMapping`. The inner value is the
    /// return value of `GetLastError`.
1396
    ErrCreateFileMappingW(uint),
A
Alex Crichton 已提交
1397 1398
    /// Unrecognized error from `MapViewOfFile`. The inner value is the return
    /// value of `GetLastError`.
1399 1400 1401
    ErrMapViewOfFile(uint)
}

1402
impl fmt::Show for MapError {
1403 1404
    fn fmt(&self, out: &mut fmt::Formatter) -> fmt::Result {
        let str = match *self {
1405 1406
            ErrFdNotAvail => "fd not available for reading or writing",
            ErrInvalidFd => "Invalid fd",
A
Alex Crichton 已提交
1407 1408 1409 1410
            ErrUnaligned => {
                "Unaligned address, invalid flags, negative length or \
                 unaligned offset"
            }
1411 1412 1413 1414 1415
            ErrNoMapSupport=> "File doesn't support mapping",
            ErrNoMem => "Invalid address, or not enough available memory",
            ErrUnsupProt => "Protection mode unsupported",
            ErrUnsupOffset => "Offset in virtual memory mode is unsupported",
            ErrAlreadyExists => "File mapping for specified file already exists",
C
Corey Richardson 已提交
1416
            ErrZeroLength => "Zero-length mapping not allowed",
A
Alex Crichton 已提交
1417
            ErrUnknown(code) => {
A
Alex Crichton 已提交
1418
                return write!(out, "Unknown error = {}", code)
A
Alex Crichton 已提交
1419 1420
            },
            ErrVirtualAlloc(code) => {
A
Alex Crichton 已提交
1421
                return write!(out, "VirtualAlloc failure = {}", code)
A
Alex Crichton 已提交
1422
            },
1423
            ErrCreateFileMappingW(code) => {
A
Alex Crichton 已提交
1424
                return write!(out, "CreateFileMappingW failure = {}", code)
1425 1426
            },
            ErrMapViewOfFile(code) => {
A
Alex Crichton 已提交
1427
                return write!(out, "MapViewOfFile failure = {}", code)
1428 1429
            }
        };
A
Alex Crichton 已提交
1430
        write!(out, "{}", str)
1431 1432 1433 1434 1435
    }
}

#[cfg(unix)]
impl MemoryMap {
A
Alex Crichton 已提交
1436 1437 1438
    /// Create a new mapping with the given `options`, at least `min_len` bytes
    /// long. `min_len` must be greater than zero; see the note on
    /// `ErrZeroLength`.
1439
    pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
1440 1441
        use libc::off_t;

C
Corey Richardson 已提交
1442 1443 1444
        if min_len == 0 {
            return Err(ErrZeroLength)
        }
1445
        let mut addr: *const u8 = ptr::null();
1446 1447 1448 1449
        let mut prot = 0;
        let mut flags = libc::MAP_PRIVATE;
        let mut fd = -1;
        let mut offset = 0;
1450
        let mut custom_flags = false;
1451
        let len = round_up(min_len, page_size());
1452

D
Daniel Micay 已提交
1453
        for &o in options.iter() {
1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465
            match o {
                MapReadable => { prot |= libc::PROT_READ; },
                MapWritable => { prot |= libc::PROT_WRITE; },
                MapExecutable => { prot |= libc::PROT_EXEC; },
                MapAddr(addr_) => {
                    flags |= libc::MAP_FIXED;
                    addr = addr_;
                },
                MapFd(fd_) => {
                    flags |= libc::MAP_FILE;
                    fd = fd_;
                },
1466 1467
                MapOffset(offset_) => { offset = offset_ as off_t; },
                MapNonStandardFlags(f) => { custom_flags = true; flags = f },
1468 1469
            }
        }
1470
        if fd == -1 && !custom_flags { flags |= libc::MAP_ANON; }
1471 1472

        let r = unsafe {
1473 1474
            libc::mmap(addr as *mut c_void, len as libc::size_t, prot, flags,
                       fd, offset)
1475
        };
1476
        if r == libc::MAP_FAILED {
1477 1478 1479 1480 1481 1482
            Err(match errno() as c_int {
                libc::EACCES => ErrFdNotAvail,
                libc::EBADF => ErrInvalidFd,
                libc::EINVAL => ErrUnaligned,
                libc::ENODEV => ErrNoMapSupport,
                libc::ENOMEM => ErrNoMem,
1483
                code => ErrUnknown(code as int)
1484 1485
            })
        } else {
1486
            Ok(MemoryMap {
1487 1488 1489 1490 1491 1492 1493 1494 1495 1496
               data: r as *mut u8,
               len: len,
               kind: if fd == -1 {
                   MapVirtual
               } else {
                   MapFile(ptr::null())
               }
            })
        }
    }
V
Vadim Chugunov 已提交
1497

A
Alex Crichton 已提交
1498 1499
    /// Granularity that the offset or address must be for `MapOffset` and
    /// `MapAddr` respectively.
V
Vadim Chugunov 已提交
1500 1501 1502
    pub fn granularity() -> uint {
        page_size()
    }
1503 1504 1505 1506
}

#[cfg(unix)]
impl Drop for MemoryMap {
C
Corey Richardson 已提交
1507
    /// Unmap the mapping. Fails the task if `munmap` fails.
D
Daniel Micay 已提交
1508
    fn drop(&mut self) {
C
Corey Richardson 已提交
1509 1510
        if self.len == 0 { /* workaround for dummy_stack */ return; }

1511
        unsafe {
1512 1513
            // `munmap` only fails due to logic errors
            libc::munmap(self.data as *mut c_void, self.len as libc::size_t);
1514 1515 1516 1517 1518 1519
        }
    }
}

#[cfg(windows)]
impl MemoryMap {
C
Corey Richardson 已提交
1520
    /// Create a new mapping with the given `options`, at least `min_len` bytes long.
1521
    pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
1522 1523 1524 1525 1526 1527 1528 1529
        use libc::types::os::arch::extra::{LPVOID, DWORD, SIZE_T, HANDLE};

        let mut lpAddress: LPVOID = ptr::mut_null();
        let mut readable = false;
        let mut writable = false;
        let mut executable = false;
        let mut fd: c_int = -1;
        let mut offset: uint = 0;
1530
        let len = round_up(min_len, page_size());
1531

D
Daniel Micay 已提交
1532
        for &o in options.iter() {
1533 1534 1535 1536 1537 1538
            match o {
                MapReadable => { readable = true; },
                MapWritable => { writable = true; },
                MapExecutable => { executable = true; }
                MapAddr(addr_) => { lpAddress = addr_ as LPVOID; },
                MapFd(fd_) => { fd = fd_; },
1539
                MapOffset(offset_) => { offset = offset_; },
A
Alex Crichton 已提交
1540
                MapNonStandardFlags(..) => {}
1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559
            }
        }

        let flProtect = match (executable, readable, writable) {
            (false, false, false) if fd == -1 => libc::PAGE_NOACCESS,
            (false, true, false) => libc::PAGE_READONLY,
            (false, true, true) => libc::PAGE_READWRITE,
            (true, false, false) if fd == -1 => libc::PAGE_EXECUTE,
            (true, true, false) => libc::PAGE_EXECUTE_READ,
            (true, true, true) => libc::PAGE_EXECUTE_READWRITE,
            _ => return Err(ErrUnsupProt)
        };

        if fd == -1 {
            if offset != 0 {
                return Err(ErrUnsupOffset);
            }
            let r = unsafe {
                libc::VirtualAlloc(lpAddress,
1560
                                   len as SIZE_T,
1561 1562 1563 1564 1565
                                   libc::MEM_COMMIT | libc::MEM_RESERVE,
                                   flProtect)
            };
            match r as uint {
                0 => Err(ErrVirtualAlloc(errno())),
1566
                _ => Ok(MemoryMap {
1567 1568 1569 1570 1571 1572
                   data: r as *mut u8,
                   len: len,
                   kind: MapVirtual
                })
            }
        } else {
V
Vadim Chugunov 已提交
1573 1574 1575 1576 1577 1578 1579
            let dwDesiredAccess = match (executable, readable, writable) {
                (false, true, false) => libc::FILE_MAP_READ,
                (false, true, true) => libc::FILE_MAP_WRITE,
                (true, true, false) => libc::FILE_MAP_READ | libc::FILE_MAP_EXECUTE,
                (true, true, true) => libc::FILE_MAP_WRITE | libc::FILE_MAP_EXECUTE,
                _ => return Err(ErrUnsupProt) // Actually, because of the check above,
                                              // we should never get here.
1580 1581 1582 1583 1584 1585
            };
            unsafe {
                let hFile = libc::get_osfhandle(fd) as HANDLE;
                let mapping = libc::CreateFileMappingW(hFile,
                                                       ptr::mut_null(),
                                                       flProtect,
V
Vadim Chugunov 已提交
1586 1587
                                                       0,
                                                       0,
1588 1589 1590 1591 1592 1593 1594 1595 1596
                                                       ptr::null());
                if mapping == ptr::mut_null() {
                    return Err(ErrCreateFileMappingW(errno()));
                }
                if errno() as c_int == libc::ERROR_ALREADY_EXISTS {
                    return Err(ErrAlreadyExists);
                }
                let r = libc::MapViewOfFile(mapping,
                                            dwDesiredAccess,
V
Vadim Chugunov 已提交
1597
                                            ((len as u64) >> 32) as DWORD,
1598 1599 1600 1601
                                            (offset & 0xffff_ffff) as DWORD,
                                            0);
                match r as uint {
                    0 => Err(ErrMapViewOfFile(errno())),
1602
                    _ => Ok(MemoryMap {
1603 1604
                       data: r as *mut u8,
                       len: len,
1605
                       kind: MapFile(mapping as *const u8)
1606 1607 1608 1609 1610
                    })
                }
            }
        }
    }
V
Vadim Chugunov 已提交
1611 1612 1613 1614

    /// Granularity of MapAddr() and MapOffset() parameter values.
    /// This may be greater than the value returned by page_size().
    pub fn granularity() -> uint {
1615
        use mem;
V
Vadim Chugunov 已提交
1616
        unsafe {
1617
            let mut info = mem::zeroed();
V
Vadim Chugunov 已提交
1618 1619 1620 1621 1622
            libc::GetSystemInfo(&mut info);

            return info.dwAllocationGranularity as uint;
        }
    }
1623 1624 1625 1626
}

#[cfg(windows)]
impl Drop for MemoryMap {
A
Alex Crichton 已提交
1627 1628
    /// Unmap the mapping. Fails the task if any of `VirtualFree`,
    /// `UnmapViewOfFile`, or `CloseHandle` fail.
D
Daniel Micay 已提交
1629
    fn drop(&mut self) {
1630
        use libc::types::os::arch::extra::{LPCVOID, HANDLE};
V
Vadim Chugunov 已提交
1631
        use libc::consts::os::extra::FALSE;
A
Alex Crichton 已提交
1632
        if self.len == 0 { return }
1633 1634 1635

        unsafe {
            match self.kind {
V
Vadim Chugunov 已提交
1636
                MapVirtual => {
1637
                    if libc::VirtualFree(self.data as *mut c_void, 0,
A
Alex Crichton 已提交
1638
                                         libc::MEM_RELEASE) == 0 {
A
Alex Crichton 已提交
1639
                        println!("VirtualFree failed: {}", errno());
V
Vadim Chugunov 已提交
1640
                    }
1641 1642
                },
                MapFile(mapping) => {
V
Vadim Chugunov 已提交
1643
                    if libc::UnmapViewOfFile(self.data as LPCVOID) == FALSE {
A
Alex Crichton 已提交
1644
                        println!("UnmapViewOfFile failed: {}", errno());
1645
                    }
V
Vadim Chugunov 已提交
1646
                    if libc::CloseHandle(mapping as HANDLE) == FALSE {
A
Alex Crichton 已提交
1647
                        println!("CloseHandle failed: {}", errno());
1648 1649 1650 1651 1652 1653 1654
                    }
                }
            }
        }
    }
}

1655 1656 1657 1658 1659 1660 1661 1662 1663
impl MemoryMap {
    /// Returns the pointer to the memory created or modified by this map.
    pub fn data(&self) -> *mut u8 { self.data }
    /// Returns the number of bytes this map applies to.
    pub fn len(&self) -> uint { self.len }
    /// Returns the type of mapping this represents.
    pub fn kind(&self) -> MemoryMapKind { self.kind }
}

1664
#[cfg(target_os = "linux")]
1665
pub mod consts {
1666
    pub use os::arch_consts::ARCH;
1667

1668
    pub static FAMILY: &'static str = "unix";
1669

1670 1671 1672
    /// A string describing the specific operating system in use: in this
    /// case, `linux`.
    pub static SYSNAME: &'static str = "linux";
I
ILyoan 已提交
1673

1674 1675 1676
    /// Specifies the filename prefix used for shared libraries on this
    /// platform: in this case, `lib`.
    pub static DLL_PREFIX: &'static str = "lib";
I
ILyoan 已提交
1677

1678 1679 1680
    /// Specifies the filename suffix used for shared libraries on this
    /// platform: in this case, `.so`.
    pub static DLL_SUFFIX: &'static str = ".so";
I
ILyoan 已提交
1681

1682 1683 1684
    /// Specifies the file extension used for shared libraries on this
    /// platform that goes after the dot: in this case, `so`.
    pub static DLL_EXTENSION: &'static str = "so";
K
kyeongwoon 已提交
1685

1686 1687 1688
    /// Specifies the filename suffix used for executable binaries on this
    /// platform: in this case, the empty string.
    pub static EXE_SUFFIX: &'static str = "";
1689

1690 1691 1692 1693
    /// Specifies the file extension, if any, used for executable binaries
    /// on this platform: in this case, the empty string.
    pub static EXE_EXTENSION: &'static str = "";
}
1694

1695 1696
#[cfg(target_os = "macos")]
pub mod consts {
1697
    pub use os::arch_consts::ARCH;
1698

1699
    pub static FAMILY: &'static str = "unix";
1700

1701 1702 1703
    /// A string describing the specific operating system in use: in this
    /// case, `macos`.
    pub static SYSNAME: &'static str = "macos";
1704

1705 1706 1707
    /// Specifies the filename prefix used for shared libraries on this
    /// platform: in this case, `lib`.
    pub static DLL_PREFIX: &'static str = "lib";
1708

1709 1710 1711
    /// Specifies the filename suffix used for shared libraries on this
    /// platform: in this case, `.dylib`.
    pub static DLL_SUFFIX: &'static str = ".dylib";
1712

1713 1714 1715
    /// Specifies the file extension used for shared libraries on this
    /// platform that goes after the dot: in this case, `dylib`.
    pub static DLL_EXTENSION: &'static str = "dylib";
1716

1717 1718
    /// Specifies the filename suffix used for executable binaries on this
    /// platform: in this case, the empty string.
V
Valerii Hiora 已提交
1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737
    pub static EXE_SUFFIX: &'static str = "";

    /// Specifies the file extension, if any, used for executable binaries
    /// on this platform: in this case, the empty string.
    pub static EXE_EXTENSION: &'static str = "";
}

#[cfg(target_os = "ios")]
pub mod consts {
    pub use os::arch_consts::ARCH;

    pub static FAMILY: &'static str = "unix";

    /// A string describing the specific operating system in use: in this
    /// case, `ios`.
    pub static SYSNAME: &'static str = "ios";

    /// Specifies the filename suffix used for executable binaries on this
    /// platform: in this case, the empty string.
1738
    pub static EXE_SUFFIX: &'static str = "";
1739

1740 1741 1742 1743
    /// Specifies the file extension, if any, used for executable binaries
    /// on this platform: in this case, the empty string.
    pub static EXE_EXTENSION: &'static str = "";
}
1744

1745 1746
#[cfg(target_os = "freebsd")]
pub mod consts {
1747
    pub use os::arch_consts::ARCH;
1748

1749
    pub static FAMILY: &'static str = "unix";
1750

1751 1752 1753
    /// A string describing the specific operating system in use: in this
    /// case, `freebsd`.
    pub static SYSNAME: &'static str = "freebsd";
I
ILyoan 已提交
1754

1755 1756 1757
    /// Specifies the filename prefix used for shared libraries on this
    /// platform: in this case, `lib`.
    pub static DLL_PREFIX: &'static str = "lib";
1758

1759 1760 1761
    /// Specifies the filename suffix used for shared libraries on this
    /// platform: in this case, `.so`.
    pub static DLL_SUFFIX: &'static str = ".so";
1762

1763 1764 1765
    /// Specifies the file extension used for shared libraries on this
    /// platform that goes after the dot: in this case, `so`.
    pub static DLL_EXTENSION: &'static str = "so";
1766

1767 1768 1769
    /// Specifies the filename suffix used for executable binaries on this
    /// platform: in this case, the empty string.
    pub static EXE_SUFFIX: &'static str = "";
1770

1771 1772 1773 1774
    /// Specifies the file extension, if any, used for executable binaries
    /// on this platform: in this case, the empty string.
    pub static EXE_EXTENSION: &'static str = "";
}
1775

1776 1777
#[cfg(target_os = "android")]
pub mod consts {
1778
    pub use os::arch_consts::ARCH;
I
ILyoan 已提交
1779

1780
    pub static FAMILY: &'static str = "unix";
1781

1782 1783 1784
    /// A string describing the specific operating system in use: in this
    /// case, `android`.
    pub static SYSNAME: &'static str = "android";
1785

1786 1787 1788
    /// Specifies the filename prefix used for shared libraries on this
    /// platform: in this case, `lib`.
    pub static DLL_PREFIX: &'static str = "lib";
1789

1790 1791 1792
    /// Specifies the filename suffix used for shared libraries on this
    /// platform: in this case, `.so`.
    pub static DLL_SUFFIX: &'static str = ".so";
1793

1794 1795 1796
    /// Specifies the file extension used for shared libraries on this
    /// platform that goes after the dot: in this case, `so`.
    pub static DLL_EXTENSION: &'static str = "so";
1797

1798 1799 1800
    /// Specifies the filename suffix used for executable binaries on this
    /// platform: in this case, the empty string.
    pub static EXE_SUFFIX: &'static str = "";
K
kyeongwoon 已提交
1801

1802 1803 1804 1805
    /// Specifies the file extension, if any, used for executable binaries
    /// on this platform: in this case, the empty string.
    pub static EXE_EXTENSION: &'static str = "";
}
1806

1807 1808
#[cfg(target_os = "win32")]
pub mod consts {
1809
    pub use os::arch_consts::ARCH;
1810

1811
    pub static FAMILY: &'static str = "windows";
1812

1813 1814 1815
    /// A string describing the specific operating system in use: in this
    /// case, `win32`.
    pub static SYSNAME: &'static str = "win32";
1816

1817 1818 1819
    /// Specifies the filename prefix used for shared libraries on this
    /// platform: in this case, the empty string.
    pub static DLL_PREFIX: &'static str = "";
1820

1821 1822 1823
    /// Specifies the filename suffix used for shared libraries on this
    /// platform: in this case, `.dll`.
    pub static DLL_SUFFIX: &'static str = ".dll";
1824

1825 1826 1827
    /// Specifies the file extension used for shared libraries on this
    /// platform that goes after the dot: in this case, `dll`.
    pub static DLL_EXTENSION: &'static str = "dll";
1828

1829 1830 1831
    /// Specifies the filename suffix used for executable binaries on this
    /// platform: in this case, `.exe`.
    pub static EXE_SUFFIX: &'static str = ".exe";
1832

1833 1834 1835 1836
    /// Specifies the file extension, if any, used for executable binaries
    /// on this platform: in this case, `exe`.
    pub static EXE_EXTENSION: &'static str = "exe";
}
1837

1838 1839 1840 1841
#[cfg(target_arch = "x86")]
mod arch_consts {
    pub static ARCH: &'static str = "x86";
}
1842

1843 1844 1845 1846
#[cfg(target_arch = "x86_64")]
mod arch_consts {
    pub static ARCH: &'static str = "x86_64";
}
1847

1848 1849 1850 1851
#[cfg(target_arch = "arm")]
mod arch_consts {
    pub static ARCH: &'static str = "arm";
}
I
ILyoan 已提交
1852

1853 1854 1855
#[cfg(target_arch = "mips")]
mod arch_consts {
    pub static ARCH: &'static str = "mips";
I
ILyoan 已提交
1856
}
1857

1858 1859 1860 1861
#[cfg(target_arch = "mipsel")]
mod arch_consts {
    pub static ARCH: &'static str = "mipsel";
}
1862

1863 1864
#[cfg(test)]
mod tests {
1865
    use prelude::*;
1866
    use c_str::ToCStr;
1867
    use option;
K
Kevin Ballard 已提交
1868
    use os::{env, getcwd, getenv, make_absolute};
1869
    use os::{split_paths, join_paths, setenv, unsetenv};
1870
    use os;
1871
    use rand::Rng;
1872
    use rand;
1873

1874
    #[test]
1875
    pub fn last_os_error() {
1876
        debug!("{}", os::last_os_error());
1877
    }
1878

1879
    fn make_rand_name() -> String {
H
Huon Wilson 已提交
1880
        let mut rng = rand::task_rng();
A
Alex Crichton 已提交
1881 1882
        let n = format!("TEST{}", rng.gen_ascii_chars().take(10u)
                                     .collect::<String>());
1883
        assert!(getenv(n.as_slice()).is_none());
1884
        n
1885 1886
    }

1887 1888 1889 1890 1891
    #[test]
    fn test_num_cpus() {
        assert!(os::num_cpus() > 0);
    }

1892 1893 1894
    #[test]
    fn test_setenv() {
        let n = make_rand_name();
1895
        setenv(n.as_slice(), "VALUE");
1896
        assert_eq!(getenv(n.as_slice()), option::Some("VALUE".to_string()));
1897 1898
    }

C
Corey Richardson 已提交
1899 1900 1901
    #[test]
    fn test_unsetenv() {
        let n = make_rand_name();
1902 1903 1904
        setenv(n.as_slice(), "VALUE");
        unsetenv(n.as_slice());
        assert_eq!(getenv(n.as_slice()), option::None);
C
Corey Richardson 已提交
1905 1906
    }

1907
    #[test]
1908
    #[ignore]
1909 1910
    fn test_setenv_overwrite() {
        let n = make_rand_name();
1911 1912
        setenv(n.as_slice(), "1");
        setenv(n.as_slice(), "2");
1913
        assert_eq!(getenv(n.as_slice()), option::Some("2".to_string()));
1914
        setenv(n.as_slice(), "");
1915
        assert_eq!(getenv(n.as_slice()), option::Some("".to_string()));
1916 1917 1918 1919 1920
    }

    // Windows GetEnvironmentVariable requires some extra work to make sure
    // the buffer the variable is copied into is the right size
    #[test]
1921
    #[ignore]
1922
    fn test_getenv_big() {
1923
        let mut s = "".to_string();
1924
        let mut i = 0i;
1925
        while i < 100 {
1926
            s.push_str("aaaaaaaaaa");
1927 1928
            i += 1;
        }
1929
        let n = make_rand_name();
1930
        setenv(n.as_slice(), s.as_slice());
1931
        debug!("{}", s.clone());
1932
        assert_eq!(getenv(n.as_slice()), option::Some(s));
1933 1934
    }

B
Ben Noordhuis 已提交
1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945
    #[test]
    fn test_self_exe_name() {
        let path = os::self_exe_name();
        assert!(path.is_some());
        let path = path.unwrap();
        debug!("{:?}", path.clone());

        // Hard to test this function
        assert!(path.is_absolute());
    }

1946 1947 1948
    #[test]
    fn test_self_exe_path() {
        let path = os::self_exe_path();
P
Patrick Walton 已提交
1949
        assert!(path.is_some());
1950
        let path = path.unwrap();
1951
        debug!("{:?}", path.clone());
1952 1953

        // Hard to test this function
1954
        assert!(path.is_absolute());
1955 1956 1957
    }

    #[test]
1958
    #[ignore]
1959 1960
    fn test_env_getenv() {
        let e = env();
Y
Youngmin Yoo 已提交
1961
        assert!(e.len() > 0u);
D
Daniel Micay 已提交
1962
        for p in e.iter() {
1963
            let (n, v) = (*p).clone();
1964
            debug!("{:?}", n.clone());
1965
            let v2 = getenv(n.as_slice());
1966 1967 1968
            // MingW seems to set some funky environment variables like
            // "=C:=C:\MinGW\msys\1.0\bin" and "!::=::\" that are returned
            // from env() but not visible from getenv().
P
Patrick Walton 已提交
1969
            assert!(v2.is_none() || v2 == option::Some(v));
1970 1971 1972
        }
    }

1973 1974 1975
    #[test]
    fn test_env_set_get_huge() {
        let n = make_rand_name();
1976
        let s = "x".repeat(10000).to_string();
1977 1978 1979 1980
        setenv(n.as_slice(), s.as_slice());
        assert_eq!(getenv(n.as_slice()), Some(s));
        unsetenv(n.as_slice());
        assert_eq!(getenv(n.as_slice()), None);
1981 1982
    }

1983 1984 1985 1986
    #[test]
    fn test_env_setenv() {
        let n = make_rand_name();

1987
        let mut e = env();
1988
        setenv(n.as_slice(), "VALUE");
1989
        assert!(!e.contains(&(n.clone(), "VALUE".to_string())));
1990 1991

        e = env();
1992
        assert!(e.contains(&(n, "VALUE".to_string())));
1993 1994
    }

1995 1996
    #[test]
    fn test() {
1997
        assert!((!Path::new("test-path").is_absolute()));
1998

1999
        let cwd = getcwd();
2000
        debug!("Current working directory: {}", cwd.display());
2001

2002 2003
        debug!("{:?}", make_absolute(&Path::new("test-path")));
        debug!("{:?}", make_absolute(&Path::new("/usr/bin")));
2004 2005 2006
    }

    #[test]
2007
    #[cfg(unix)]
2008
    fn homedir() {
E
Erick Tryzelaar 已提交
2009
        let oldhome = getenv("HOME");
2010

E
Erick Tryzelaar 已提交
2011
        setenv("HOME", "/home/MountainView");
2012
        assert!(os::homedir() == Some(Path::new("/home/MountainView")));
2013

E
Erick Tryzelaar 已提交
2014
        setenv("HOME", "");
P
Patrick Walton 已提交
2015
        assert!(os::homedir().is_none());
2016

2017
        for s in oldhome.iter() {
A
Axel Viala 已提交
2018
            setenv("HOME", s.as_slice());
2019
        }
2020 2021 2022
    }

    #[test]
2023
    #[cfg(windows)]
2024 2025
    fn homedir() {

E
Erick Tryzelaar 已提交
2026 2027
        let oldhome = getenv("HOME");
        let olduserprofile = getenv("USERPROFILE");
2028

E
Erick Tryzelaar 已提交
2029 2030
        setenv("HOME", "");
        setenv("USERPROFILE", "");
2031

P
Patrick Walton 已提交
2032
        assert!(os::homedir().is_none());
2033

E
Erick Tryzelaar 已提交
2034
        setenv("HOME", "/home/MountainView");
2035
        assert!(os::homedir() == Some(Path::new("/home/MountainView")));
2036

E
Erick Tryzelaar 已提交
2037
        setenv("HOME", "");
2038

E
Erick Tryzelaar 已提交
2039
        setenv("USERPROFILE", "/home/MountainView");
2040
        assert!(os::homedir() == Some(Path::new("/home/MountainView")));
2041

E
Erick Tryzelaar 已提交
2042 2043
        setenv("HOME", "/home/MountainView");
        setenv("USERPROFILE", "/home/PaloAlto");
2044
        assert!(os::homedir() == Some(Path::new("/home/MountainView")));
2045

2046
        for s in oldhome.iter() {
A
Axel Viala 已提交
2047
            setenv("HOME", s.as_slice());
2048 2049
        }
        for s in olduserprofile.iter() {
A
Axel Viala 已提交
2050
            setenv("USERPROFILE", s.as_slice());
2051
        }
2052 2053
    }

2054 2055 2056 2057
    #[test]
    fn memory_map_rw() {
        use result::{Ok, Err};

2058
        let chunk = match os::MemoryMap::new(16, [
2059 2060 2061 2062
            os::MapReadable,
            os::MapWritable
        ]) {
            Ok(chunk) => chunk,
C
Corey Richardson 已提交
2063
            Err(msg) => fail!("{}", msg)
2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077
        };
        assert!(chunk.len >= 16);

        unsafe {
            *chunk.data = 0xBE;
            assert!(*chunk.data == 0xBE);
        }
    }

    #[test]
    fn memory_map_file() {
        use result::{Ok, Err};
        use os::*;
        use libc::*;
A
Alex Crichton 已提交
2078
        use io::fs;
2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092

        #[cfg(unix)]
        fn lseek_(fd: c_int, size: uint) {
            unsafe {
                assert!(lseek(fd, size as off_t, SEEK_SET) == size as off_t);
            }
        }
        #[cfg(windows)]
        fn lseek_(fd: c_int, size: uint) {
           unsafe {
               assert!(lseek(fd, size as c_long, SEEK_SET) == size as c_long);
           }
        }

2093
        let mut path = tmpdir();
2094
        path.push("mmap_file.tmp");
V
Vadim Chugunov 已提交
2095
        let size = MemoryMap::granularity() * 2;
2096 2097

        let fd = unsafe {
2098
            let fd = path.with_c_str(|path| {
2099
                open(path, O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR)
2100
            });
2101
            lseek_(fd, size);
2102
            "x".with_c_str(|x| assert!(write(fd, x as *const c_void, 1) == 1));
2103 2104
            fd
        };
2105
        let chunk = match MemoryMap::new(size / 2, [
2106 2107 2108 2109 2110 2111
            MapReadable,
            MapWritable,
            MapFd(fd),
            MapOffset(size / 2)
        ]) {
            Ok(chunk) => chunk,
2112
            Err(msg) => fail!("{}", msg)
2113 2114 2115 2116 2117 2118 2119 2120
        };
        assert!(chunk.len > 0);

        unsafe {
            *chunk.data = 0xbe;
            assert!(*chunk.data == 0xbe);
            close(fd);
        }
2121
        drop(chunk);
2122

2123
        fs::unlink(&path).unwrap();
2124 2125
    }

A
Aaron Turon 已提交
2126 2127 2128 2129 2130 2131 2132 2133
    #[test]
    #[cfg(windows)]
    fn split_paths_windows() {
        fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
            split_paths(unparsed) ==
                parsed.iter().map(|s| Path::new(*s)).collect()
        }

2134 2135 2136
        assert!(check_parse("", [""]));
        assert!(check_parse(r#""""#, [""]));
        assert!(check_parse(";;", ["", "", ""]));
A
Aaron Turon 已提交
2137
        assert!(check_parse(r"c:\", [r"c:\"]));
2138
        assert!(check_parse(r"c:\;", [r"c:\", ""]));
A
Aaron Turon 已提交
2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153
        assert!(check_parse(r"c:\;c:\Program Files\",
                            [r"c:\", r"c:\Program Files\"]));
        assert!(check_parse(r#"c:\;c:\"foo"\"#, [r"c:\", r"c:\foo\"]));
        assert!(check_parse(r#"c:\;c:\"foo;bar"\;c:\baz"#,
                            [r"c:\", r"c:\foo;bar\", r"c:\baz"]));
    }

    #[test]
    #[cfg(unix)]
    fn split_paths_unix() {
        fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
            split_paths(unparsed) ==
                parsed.iter().map(|s| Path::new(*s)).collect()
        }

2154 2155
        assert!(check_parse("", [""]));
        assert!(check_parse("::", ["", "", ""]));
A
Aaron Turon 已提交
2156
        assert!(check_parse("/", ["/"]));
2157
        assert!(check_parse("/:", ["/", ""]));
A
Aaron Turon 已提交
2158 2159 2160
        assert!(check_parse("/:/usr/local", ["/", "/usr/local"]));
    }

2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192
    #[test]
    #[cfg(unix)]
    fn join_paths_unix() {
        fn test_eq(input: &[&str], output: &str) -> bool {
            join_paths(input).unwrap().as_slice() == output.as_bytes()
        }

        assert!(test_eq([], ""));
        assert!(test_eq(["/bin", "/usr/bin", "/usr/local/bin"],
                        "/bin:/usr/bin:/usr/local/bin"));
        assert!(test_eq(["", "/bin", "", "", "/usr/bin", ""],
                        ":/bin:::/usr/bin:"));
        assert!(join_paths(["/te:st"]).is_err());
    }

    #[test]
    #[cfg(windows)]
    fn join_paths_windows() {
        fn test_eq(input: &[&str], output: &str) -> bool {
            join_paths(input).unwrap().as_slice() == output.as_bytes()
        }

        assert!(test_eq([], ""));
        assert!(test_eq([r"c:\windows", r"c:\"],
                        r"c:\windows;c:\"));
        assert!(test_eq(["", r"c:\windows", "", "", r"c:\", ""],
                        r";c:\windows;;;c:\;"));
        assert!(test_eq([r"c:\te;st", r"c:\"],
                        r#""c:\te;st";c:\"#));
        assert!(join_paths([r#"c:\te"st"#]).is_err());
    }

2193
    // More recursive_mkdir tests are in extra::tempfile
2194
}