os.rs 60.1 KB
Newer Older
1
// Copyright 2012-2013 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
#[allow(missing_doc)];

31
use c_str::{CString, ToCStr};
32
use clone::Clone;
33
use container::Container;
34
use io;
35
use iter::range;
36
use libc;
A
Alex Crichton 已提交
37
use libc::{c_char, c_void, c_int, size_t};
38
use libc::FILE;
P
Patrick Walton 已提交
39
use option::{Some, None};
40
use os;
41
use prelude::*;
42 43
use ptr;
use str;
44
use to_str;
45
use unstable::finally::Finally;
46
use vec;
47

48
pub use libc::fclose;
49
pub use os::consts::*;
50

51
/// Delegates to the libc close() function, returning the same return value.
52
pub fn close(fd: c_int) -> c_int {
53
    #[fixed_stack_segment]; #[inline(never)];
54 55 56 57 58
    unsafe {
        libc::close(fd)
    }
}

59 60 61 62
pub mod rustrt {
    use libc::{c_char, c_int};
    use libc;

63
    extern {
64 65
        pub fn rust_path_is_dir(path: *libc::c_char) -> c_int;
        pub fn rust_path_exists(path: *libc::c_char) -> c_int;
66
    }
67 68
}

69 70
pub static TMPBUF_SZ : uint = 1000u;
static BUF_BYTES : uint = 2048u;
71

72
pub fn getcwd() -> Path {
73
    #[fixed_stack_segment]; #[inline(never)];
74 75 76 77
    let mut buf = [0 as libc::c_char, ..BUF_BYTES];
    do buf.as_mut_buf |buf, len| {
        unsafe {
            if libc::getcwd(buf, len as size_t).is_null() {
A
Alex Crichton 已提交
78
                fail2!()
79 80
            }

81
            Path::new(CString::new(buf as *c_char, false))
82 83 84 85
        }
    }
}

86
#[cfg(windows)]
87
pub mod win32 {
88 89 90
    use libc;
    use vec;
    use str;
91
    use option::{None, Option};
92
    use option;
93
    use os::TMPBUF_SZ;
94
    use libc::types::os::arch::extra::DWORD;
95

96
    pub fn fill_utf16_buf_and_decode(f: &fn(*mut u16, DWORD) -> DWORD)
B
Brian Anderson 已提交
97
        -> Option<~str> {
98 99
        #[fixed_stack_segment]; #[inline(never)];

100
        unsafe {
101
            let mut n = TMPBUF_SZ as DWORD;
102 103 104
            let mut res = None;
            let mut done = false;
            while !done {
105
                let mut k: DWORD = 0;
106
                let mut buf = vec::from_elem(n as uint, 0u16);
107
                do buf.as_mut_buf |b, _sz| {
108
                    k = f(b, TMPBUF_SZ as DWORD);
109 110 111 112 113 114 115 116 117
                    if k == (0 as DWORD) {
                        done = true;
                    } else if (k == n &&
                               libc::GetLastError() ==
                               libc::ERROR_INSUFFICIENT_BUFFER as DWORD) {
                        n *= (2 as DWORD);
                    } else {
                        done = true;
                    }
118
                }
119
                if k != 0 && done {
120
                    let sub = buf.slice(0, k as uint);
121 122
                    res = option::Some(str::from_utf16(sub));
                }
123
            }
124
            return res;
125 126 127
        }
    }

128
    pub fn as_utf16_p<T>(s: &str, f: &fn(*u16) -> T) -> T {
129
        let mut t = s.to_utf16();
130
        // Null terminate before passing on.
131
        t.push(0u16);
132
        t.as_imm_buf(|buf, _len| f(buf))
133
    }
134 135
}

136 137
/*
Accessing environment variables is not generally threadsafe.
138
Serialize access through a global lock.
139 140
*/
fn with_env_lock<T>(f: &fn() -> T) -> T {
141
    use unstable::finally::Finally;
142

143
    unsafe {
144 145 146 147 148 149 150
        return do (|| {
            rust_take_env_lock();
            f()
        }).finally {
            rust_drop_env_lock();
        };
    }
151

152 153
    externfn!(fn rust_take_env_lock());
    externfn!(fn rust_drop_env_lock());
B
Ben Blum 已提交
154 155
}

156 157
/// Returns a vector of (variable, value) pairs for all the environment
/// variables of the current process.
158 159
pub fn env() -> ~[(~str,~str)] {
    unsafe {
160 161
        #[cfg(windows)]
        unsafe fn get_env_pairs() -> ~[~str] {
162 163
            #[fixed_stack_segment]; #[inline(never)];

164 165 166 167 168 169
            use libc::funcs::extra::kernel32::{
                GetEnvironmentStringsA,
                FreeEnvironmentStringsA
            };
            let ch = GetEnvironmentStringsA();
            if (ch as uint == 0) {
A
Alex Crichton 已提交
170 171
                fail2!("os::env() failure getting env string from OS: {}",
                       os::last_os_error());
172
            }
173
            let result = str::raw::from_c_multistring(ch as *libc::c_char, None);
174 175 176 177 178
            FreeEnvironmentStringsA(ch);
            result
        }
        #[cfg(unix)]
        unsafe fn get_env_pairs() -> ~[~str] {
179 180
            #[fixed_stack_segment]; #[inline(never)];

181
            extern {
182
                fn rust_env_pairs() -> **libc::c_char;
183
            }
184
            let environ = rust_env_pairs();
185
            if (environ as uint == 0) {
A
Alex Crichton 已提交
186 187
                fail2!("os::env() failure getting env string from OS: {}",
                       os::last_os_error());
188 189 190 191
            }
            let mut result = ~[];
            ptr::array_each(environ, |e| {
                let env_pair = str::raw::from_c_str(e);
A
Alex Crichton 已提交
192
                debug2!("get_env_pairs: {}", env_pair);
193 194 195 196 197 198
                result.push(env_pair);
            });
            result
        }

        fn env_convert(input: ~[~str]) -> ~[(~str, ~str)] {
199
            let mut pairs = ~[];
D
Daniel Micay 已提交
200
            for p in input.iter() {
201
                let vs: ~[&str] = p.splitn_iter('=', 1).collect();
A
Alex Crichton 已提交
202
                debug2!("splitting: len: {}", vs.len());
203
                assert_eq!(vs.len(), 2);
204
                pairs.push((vs[0].to_owned(), vs[1].to_owned()));
205
            }
L
Luqman Aden 已提交
206
            pairs
207
        }
208 209 210 211
        do with_env_lock {
            let unparsed_environ = get_env_pairs();
            env_convert(unparsed_environ)
        }
212
    }
213
}
214

215
#[cfg(unix)]
216 217
/// Fetches the environment variable `n` from the current process, returning
/// None if the variable isn't set.
218
pub fn getenv(n: &str) -> Option<~str> {
219
    #[fixed_stack_segment]; #[inline(never)];
220 221
    unsafe {
        do with_env_lock {
K
Kevin Ballard 已提交
222
            let s = do n.with_c_str |buf| {
223 224
                libc::getenv(buf)
            };
225
            if s.is_null() {
226
                None
227
            } else {
228
                Some(str::raw::from_c_str(s))
229
            }
230
        }
231 232
    }
}
233

234
#[cfg(windows)]
235 236
/// Fetches the environment variable `n` from the current process, returning
/// None if the variable isn't set.
237
pub fn getenv(n: &str) -> Option<~str> {
238 239
    #[fixed_stack_segment]; #[inline(never)];

240 241 242 243 244 245
    unsafe {
        do with_env_lock {
            use os::win32::{as_utf16_p, fill_utf16_buf_and_decode};
            do as_utf16_p(n) |u| {
                do fill_utf16_buf_and_decode() |buf, sz| {
                    libc::GetEnvironmentVariableW(u, buf, sz)
246 247 248
                }
            }
        }
249 250
    }
}
251 252


253
#[cfg(unix)]
254 255
/// Sets the environment variable `n` to the value `v` for the currently running
/// process
256
pub fn setenv(n: &str, v: &str) {
257
    #[fixed_stack_segment]; #[inline(never)];
258 259
    unsafe {
        do with_env_lock {
K
Kevin Ballard 已提交
260 261
            do n.with_c_str |nbuf| {
                do v.with_c_str |vbuf| {
262
                    libc::funcs::posix01::unistd::setenv(nbuf, vbuf, 1);
263 264 265
                }
            }
        }
266 267
    }
}
268 269


270
#[cfg(windows)]
271 272
/// Sets the environment variable `n` to the value `v` for the currently running
/// process
273
pub fn setenv(n: &str, v: &str) {
274 275
    #[fixed_stack_segment]; #[inline(never)];

276 277 278 279 280 281
    unsafe {
        do with_env_lock {
            use os::win32::as_utf16_p;
            do as_utf16_p(n) |nbuf| {
                do as_utf16_p(v) |vbuf| {
                    libc::SetEnvironmentVariableW(nbuf, vbuf);
282 283 284 285 286 287
                }
            }
        }
    }
}

C
Corey Richardson 已提交
288 289 290 291
/// Remove a variable from the environment entirely
pub fn unsetenv(n: &str) {
    #[cfg(unix)]
    fn _unsetenv(n: &str) {
292
        #[fixed_stack_segment]; #[inline(never)];
C
Corey Richardson 已提交
293 294
        unsafe {
            do with_env_lock {
K
Kevin Ballard 已提交
295
                do n.with_c_str |nbuf| {
C
Corey Richardson 已提交
296 297 298 299 300 301 302
                    libc::funcs::posix01::unistd::unsetenv(nbuf);
                }
            }
        }
    }
    #[cfg(windows)]
    fn _unsetenv(n: &str) {
303
        #[fixed_stack_segment]; #[inline(never)];
C
Corey Richardson 已提交
304 305 306 307 308 309 310 311 312 313 314 315 316
        unsafe {
            do with_env_lock {
                use os::win32::as_utf16_p;
                do as_utf16_p(n) |nbuf| {
                    libc::SetEnvironmentVariableW(nbuf, ptr::null());
                }
            }
        }
    }

    _unsetenv(n);
}

317
pub fn fdopen(fd: c_int) -> *FILE {
318
    #[fixed_stack_segment]; #[inline(never)];
K
Kevin Ballard 已提交
319
    do "r".with_c_str |modebuf| {
E
Erick Tryzelaar 已提交
320
        unsafe {
321
            libc::fdopen(fd, modebuf)
E
Erick Tryzelaar 已提交
322
        }
323
    }
324 325 326
}


327 328
// fsync related

329
#[cfg(windows)]
330
pub fn fsync_fd(fd: c_int, _level: io::fsync::Level) -> c_int {
331
    #[fixed_stack_segment]; #[inline(never)];
332 333 334 335
    unsafe {
        use libc::funcs::extra::msvcrt::*;
        return commit(fd);
    }
336 337 338
}

#[cfg(target_os = "linux")]
K
kyeongwoon 已提交
339
#[cfg(target_os = "android")]
340
pub fn fsync_fd(fd: c_int, level: io::fsync::Level) -> c_int {
341
    #[fixed_stack_segment]; #[inline(never)];
342 343 344 345 346 347 348
    unsafe {
        use libc::funcs::posix01::unistd::*;
        match level {
          io::fsync::FSync
          | io::fsync::FullFSync => return fsync(fd),
          io::fsync::FDataSync => return fdatasync(fd)
        }
349 350 351 352
    }
}

#[cfg(target_os = "macos")]
353
pub fn fsync_fd(fd: c_int, level: io::fsync::Level) -> c_int {
354 355
    #[fixed_stack_segment]; #[inline(never)];

356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
    unsafe {
        use libc::consts::os::extra::*;
        use libc::funcs::posix88::fcntl::*;
        use libc::funcs::posix01::unistd::*;
        match level {
          io::fsync::FSync => return fsync(fd),
          _ => {
            // According to man fnctl, the ok retval is only specified to be
            // !=-1
            if (fcntl(F_FULLFSYNC as c_int, fd) == -1 as c_int)
                { return -1 as c_int; }
            else
                { return 0 as c_int; }
          }
        }
371 372 373 374
    }
}

#[cfg(target_os = "freebsd")]
375
pub fn fsync_fd(fd: c_int, _l: io::fsync::Level) -> c_int {
376 377
    #[fixed_stack_segment]; #[inline(never)];

378 379 380 381
    unsafe {
        use libc::funcs::posix01::unistd::*;
        return fsync(fd);
    }
382 383
}

384
pub struct Pipe {
385
    input: c_int,
386 387
    out: c_int
}
388

389
#[cfg(unix)]
390
pub fn pipe() -> Pipe {
391
    #[fixed_stack_segment]; #[inline(never)];
392
    unsafe {
393
        let mut fds = Pipe {input: 0 as c_int,
394
                            out: 0 as c_int };
395 396
        assert_eq!(libc::pipe(&mut fds.input), (0 as c_int));
        return Pipe {input: fds.input, out: fds.out};
397
    }
398 399 400 401
}



402
#[cfg(windows)]
403
pub fn pipe() -> Pipe {
404
    #[fixed_stack_segment]; #[inline(never)];
405 406 407 408 409
    unsafe {
        // 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
410
        // first, as in std::run.
411
        let mut fds = Pipe {input: 0 as c_int,
412
                    out: 0 as c_int };
413
        let res = libc::pipe(&mut fds.input, 1024 as ::libc::c_uint,
414
                             (libc::O_BINARY | libc::O_NOINHERIT) as c_int);
415
        assert_eq!(res, 0 as c_int);
416 417 418
        assert!((fds.input != -1 as c_int && fds.input != 0 as c_int));
        assert!((fds.out != -1 as c_int && fds.input != 0 as c_int));
        return Pipe {input: fds.input, out: fds.out};
419
    }
420 421
}

P
Patrick Walton 已提交
422
fn dup2(src: c_int, dst: c_int) -> c_int {
423
    #[fixed_stack_segment]; #[inline(never)];
424 425 426
    unsafe {
        libc::dup2(src, dst)
    }
P
Patrick Walton 已提交
427 428
}

429
/// Returns the proper dll filename for the given basename of a file.
430
pub fn dll_filename(base: &str) -> ~str {
A
Alex Crichton 已提交
431
    format!("{}{}{}", DLL_PREFIX, base, DLL_SUFFIX)
432 433
}

434 435
/// Optionally returns the filesystem path to the current executable which is
/// running. If any failure occurs, None is returned.
436
pub fn self_exe_path() -> Option<Path> {
437 438

    #[cfg(target_os = "freebsd")]
439
    fn load_self() -> Option<~[u8]> {
440
        #[fixed_stack_segment]; #[inline(never)];
441
        unsafe {
442 443
            use libc::funcs::bsd44::*;
            use libc::consts::os::extra::*;
444 445 446 447 448 449 450 451 452 453
            let mib = ~[CTL_KERN as c_int,
                        KERN_PROC as c_int,
                        KERN_PROC_PATHNAME as c_int, -1 as c_int];
            let mut sz: size_t = 0;
            let err = sysctl(vec::raw::to_ptr(mib), mib.len() as ::libc::c_uint,
                             ptr::mut_null(), &mut sz, ptr::null(), 0u as size_t);
            if err != 0 { return None; }
            if sz == 0 { return None; }
            let mut v: ~[u8] = vec::with_capacity(sz as uint);
            let err = do v.as_mut_buf |buf,_| {
Y
Youngmin Yoo 已提交
454
                sysctl(vec::raw::to_ptr(mib), mib.len() as ::libc::c_uint,
455 456 457 458 459 460
                       buf as *mut c_void, &mut sz, ptr::null(), 0u as size_t)
            };
            if err != 0 { return None; }
            if sz == 0 { return None; }
            vec::raw::set_len(&mut v, sz as uint - 1); // chop off trailing NUL
            Some(v)
461
        }
462 463 464
    }

    #[cfg(target_os = "linux")]
K
kyeongwoon 已提交
465
    #[cfg(target_os = "android")]
466
    fn load_self() -> Option<~[u8]> {
467
        #[fixed_stack_segment]; #[inline(never)];
468 469
        unsafe {
            use libc::funcs::posix01::unistd::readlink;
470

471
            let mut path: ~[u8] = vec::with_capacity(TMPBUF_SZ);
472

473 474 475
            let len = do path.as_mut_buf |buf, _| {
                do "/proc/self/exe".with_c_str |proc_self_buf| {
                    readlink(proc_self_buf, buf as *mut c_char, TMPBUF_SZ as size_t) as uint
476
                }
477 478 479 480 481 482
            };
            if len == -1 {
                None
            } else {
                vec::raw::set_len(&mut path, len as uint);
                Some(path)
483
            }
484 485 486
        }
    }

487
    #[cfg(target_os = "macos")]
488
    fn load_self() -> Option<~[u8]> {
489
        #[fixed_stack_segment]; #[inline(never)];
490
        unsafe {
491 492 493 494 495 496 497 498 499 500 501
            use libc::funcs::extra::_NSGetExecutablePath;
            let mut sz: u32 = 0;
            _NSGetExecutablePath(ptr::mut_null(), &mut sz);
            if sz == 0 { return None; }
            let mut v: ~[u8] = vec::with_capacity(sz as uint);
            let err = do v.as_mut_buf |buf,_| {
                _NSGetExecutablePath(buf as *mut i8, &mut sz)
            };
            if err != 0 { return None; }
            vec::raw::set_len(&mut v, sz as uint - 1); // chop off trailing NUL
            Some(v)
502
        }
503 504
    }

505
    #[cfg(windows)]
506
    fn load_self() -> Option<~[u8]> {
507
        #[fixed_stack_segment]; #[inline(never)];
508 509 510 511
        unsafe {
            use os::win32::fill_utf16_buf_and_decode;
            do fill_utf16_buf_and_decode() |buf, sz| {
                libc::GetModuleFileNameW(0u as libc::DWORD, buf, sz)
K
Kevin Ballard 已提交
512
            }.map(|s| s.into_bytes())
513
        }
514 515
    }

K
Kevin Ballard 已提交
516
    load_self().and_then(|path| Path::new_opt(path).map(|mut p| { p.pop(); p }))
517 518 519 520 521
}


/**
 * Returns the path to the user's home directory, if known.
522 523 524
}


525 526 527 528 529 530 531 532 533 534 535 536 537
/**
 * Returns the path to the user's home directory, if known.
 *
 * On Unix, returns the value of the 'HOME' environment variable if it is set
 * and not equal to the empty string.
 *
 * On 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.
 *
 * Otherwise, homedir returns option::none.
 */
538
pub fn homedir() -> Option<Path> {
539
    // FIXME (#7188): getenv needs a ~[u8] variant
540
    return match getenv("HOME") {
541
        Some(ref p) if !p.is_empty() => Path::new_opt(p.as_slice()),
542
        _ => secondary()
543 544
    };

545
    #[cfg(unix)]
B
Brian Anderson 已提交
546 547
    fn secondary() -> Option<Path> {
        None
548 549
    }

550
    #[cfg(windows)]
B
Brian Anderson 已提交
551
    fn secondary() -> Option<Path> {
552
        do getenv("USERPROFILE").and_then |p| {
553
            if !p.is_empty() {
554
                Path::new_opt(p)
555
            } else {
B
Brian Anderson 已提交
556
                None
557 558 559 560 561
            }
        }
    }
}

562
/**
563
 * Returns the path to a temporary directory.
564 565 566
 *
 * On Unix, returns the value of the 'TMPDIR' environment variable if it is
 * set and non-empty and '/tmp' otherwise.
567 568
 * On Android, there is no global temporary folder (it is usually allocated
 * per-app), hence returns '/data/tmp' which is commonly used.
569 570
 *
 * On Windows, returns the value of, in order, the 'TMP', 'TEMP',
571 572
 * 'USERPROFILE' environment variable  if any are set and not the empty
 * string. Otherwise, tmpdir returns the path to the Windows directory.
573
 */
574
pub fn tmpdir() -> Path {
575 576
    return lookup();

B
Brian Anderson 已提交
577
    fn getenv_nonempty(v: &str) -> Option<Path> {
578
        match getenv(v) {
L
Luqman Aden 已提交
579
            Some(x) =>
580
                if x.is_empty() {
B
Brian Anderson 已提交
581
                    None
582
                } else {
583
                    Path::new_opt(x)
584
                },
B
Brian Anderson 已提交
585
            _ => None
586 587 588 589
        }
    }

    #[cfg(unix)]
590
    fn lookup() -> Path {
591
        if cfg!(target_os = "android") {
592
            Path::new("/data/tmp")
593
        } else {
594
            getenv_nonempty("TMPDIR").unwrap_or(Path::new("/tmp"))
595
        }
596 597 598
    }

    #[cfg(windows)]
599
    fn lookup() -> Path {
600 601 602
        getenv_nonempty("TMP").or(
            getenv_nonempty("TEMP").or(
                getenv_nonempty("USERPROFILE").or(
603
                   getenv_nonempty("WINDIR")))).unwrap_or(Path::new("C:\\Windows"))
604 605
    }
}
B
Brian Anderson 已提交
606

607
/// Recursively walk a directory structure
A
Alex Crichton 已提交
608
pub fn walk_dir(p: &Path, f: &fn(&Path) -> bool) -> bool {
609 610
    let r = list_dir(p);
    r.iter().advance(|q| {
611
        let path = &p.join(q);
612
        f(path) && (!path_is_dir(path) || walk_dir(path, |p| f(p)))
A
Alex Crichton 已提交
613 614
    })
}
615

616
/// Indicates whether a path represents a directory
617
pub fn path_is_dir(p: &Path) -> bool {
618
    #[fixed_stack_segment]; #[inline(never)];
619
    unsafe {
K
Kevin Ballard 已提交
620
        do p.with_c_str |buf| {
621 622
            rustrt::rust_path_is_dir(buf) != 0 as c_int
        }
623
    }
624 625
}

626
/// Indicates whether a path exists
627
pub fn path_exists(p: &Path) -> bool {
628
    #[fixed_stack_segment]; #[inline(never)];
629
    unsafe {
K
Kevin Ballard 已提交
630
        do p.with_c_str |buf| {
631 632
            rustrt::rust_path_exists(buf) != 0 as c_int
        }
633
    }
634 635
}

636 637 638 639 640
/**
 * 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
641
 * as is.
642
 */
643 644 645
// 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.
646
pub fn make_absolute(p: &Path) -> Path {
647 648
    if p.is_absolute() {
        p.clone()
649
    } else {
650
        let mut ret = getcwd();
651
        ret.push(p);
652
        ret
653
    }
654 655 656
}


657
/// Creates a directory at the specified path
658
pub fn make_dir(p: &Path, mode: c_int) -> bool {
B
Brian Anderson 已提交
659
    return mkdir(p, mode);
660

661
    #[cfg(windows)]
662
    fn mkdir(p: &Path, _mode: c_int) -> bool {
663
        #[fixed_stack_segment]; #[inline(never)];
664 665 666
        unsafe {
            use os::win32::as_utf16_p;
            // FIXME: turn mode into something useful? #2623
667
            do as_utf16_p(p.as_str().unwrap()) |buf| {
668
                libc::CreateDirectoryW(buf, ptr::mut_null())
669 670
                    != (0 as libc::BOOL)
            }
671
        }
672 673
    }

674
    #[cfg(unix)]
675
    fn mkdir(p: &Path, mode: c_int) -> bool {
676
        #[fixed_stack_segment]; #[inline(never)];
K
Kevin Ballard 已提交
677
        do p.with_c_str |buf| {
E
Erick Tryzelaar 已提交
678 679
            unsafe {
                libc::mkdir(buf, mode as libc::mode_t) == (0 as c_int)
680
            }
681
        }
682 683 684
    }
}

685 686 687 688
/// Creates a directory with a given mode.
/// Returns true iff creation
/// succeeded. Also creates all intermediate subdirectories
/// if they don't already exist, giving all of them the same mode.
689 690 691

// tjc: if directory exists but with different permissions,
// should we return false?
692 693 694 695
pub fn mkdir_recursive(p: &Path, mode: c_int) -> bool {
    if path_is_dir(p) {
        return true;
    }
K
Kevin Ballard 已提交
696 697 698
    if p.filename().is_some() {
        let mut p_ = p.clone();
        p_.pop();
699 700 701
        if !mkdir_recursive(&p_, mode) {
            return false;
        }
702
    }
703
    return make_dir(p, mode);
704 705
}

706
/// Lists the contents of a directory
707 708 709
///
/// Each resulting Path is a relative path with no directory component.
pub fn list_dir(p: &Path) -> ~[Path] {
710
    unsafe {
711 712 713 714
        #[cfg(target_os = "linux")]
        #[cfg(target_os = "android")]
        #[cfg(target_os = "freebsd")]
        #[cfg(target_os = "macos")]
715
        unsafe fn get_list(p: &Path) -> ~[Path] {
716
            #[fixed_stack_segment]; #[inline(never)];
A
Alex Crichton 已提交
717
            use libc::{dirent_t};
718
            use libc::{opendir, readdir, closedir};
719
            extern {
720
                fn rust_list_dir_val(ptr: *dirent_t) -> *libc::c_char;
721
            }
722
            let mut paths = ~[];
A
Alex Crichton 已提交
723
            debug2!("os::list_dir -- BEFORE OPENDIR");
724

K
Kevin Ballard 已提交
725
            let dir_ptr = do p.with_c_str |buf| {
726 727 728
                opendir(buf)
            };

729
            if (dir_ptr as uint != 0) {
A
Alex Crichton 已提交
730
                debug2!("os::list_dir -- opendir() SUCCESS");
731 732
                let mut entry_ptr = readdir(dir_ptr);
                while (entry_ptr as uint != 0) {
733
                    let cstr = CString::new(rust_list_dir_val(entry_ptr), false);
734
                    paths.push(Path::new(cstr));
735 736 737 738 739
                    entry_ptr = readdir(dir_ptr);
                }
                closedir(dir_ptr);
            }
            else {
A
Alex Crichton 已提交
740
                debug2!("os::list_dir -- opendir() FAILURE");
741
            }
742 743
            debug2!("os::list_dir -- AFTER -- \\#: {}", paths.len());
            paths
744
        }
745
        #[cfg(windows)]
746
        unsafe fn get_list(p: &Path) -> ~[Path] {
747
            #[fixed_stack_segment]; #[inline(never)];
748
            use libc::consts::os::extra::INVALID_HANDLE_VALUE;
D
Daniel Micay 已提交
749
            use libc::{wcslen, free};
750 751 752 753 754
            use libc::funcs::extra::kernel32::{
                FindFirstFileW,
                FindNextFileW,
                FindClose,
            };
755
            use libc::types::os::arch::extra::HANDLE;
756 757 758
            use os::win32::{
                as_utf16_p
            };
D
Daniel Micay 已提交
759
            use rt::global_heap::malloc_raw;
760

761
            #[nolink]
762
            extern {
763 764
                fn rust_list_dir_wfd_size() -> libc::size_t;
                fn rust_list_dir_wfd_fp_buf(wfd: *libc::c_void) -> *u16;
765
            }
766
            let star = p.join("*");
767 768
            do as_utf16_p(star.as_str().unwrap()) |path_ptr| {
                let mut paths = ~[];
769
                let wfd_ptr = malloc_raw(rust_list_dir_wfd_size() as uint);
770
                let find_handle = FindFirstFileW(path_ptr, wfd_ptr as HANDLE);
771
                if find_handle as libc::c_int != INVALID_HANDLE_VALUE {
772 773
                    let mut more_files = 1 as libc::c_int;
                    while more_files != 0 {
774
                        let fp_buf = rust_list_dir_wfd_fp_buf(wfd_ptr);
775
                        if fp_buf as uint == 0 {
A
Alex Crichton 已提交
776
                            fail2!("os::list_dir() failure: got null ptr from wfd");
777 778 779 780 781
                        }
                        else {
                            let fp_vec = vec::from_buf(
                                fp_buf, wcslen(fp_buf) as uint);
                            let fp_str = str::from_utf16(fp_vec);
782
                            paths.push(Path::new(fp_str));
783
                        }
784
                        more_files = FindNextFileW(find_handle, wfd_ptr as HANDLE);
785 786
                    }
                    FindClose(find_handle);
D
Daniel Micay 已提交
787
                    free(wfd_ptr)
788
                }
789
                paths
790 791
            }
        }
792 793
        do get_list(p).move_iter().filter |path| {
            path.as_vec() != bytes!(".") && path.as_vec() != bytes!("..")
794
        }.collect()
795 796 797
    }
}

798 799 800 801 802
/**
 * Lists the contents of a directory
 *
 * This version prepends each entry with the directory.
 */
803
pub fn list_dir_path(p: &Path) -> ~[Path] {
804
    list_dir(p).map(|f| p.join(f))
805 806
}

807 808 809 810
/// Removes a directory at the specified path, after removing
/// all its contents. Use carefully!
pub fn remove_dir_recursive(p: &Path) -> bool {
    let mut error_happened = false;
811
    do walk_dir(p) |inner| {
812 813 814 815 816 817 818 819 820 821 822 823
        if !error_happened {
            if path_is_dir(inner) {
                if !remove_dir_recursive(inner) {
                    error_happened = true;
                }
            }
            else {
                if !remove_file(inner) {
                    error_happened = true;
                }
            }
        }
824
        true
825 826 827 828 829
    };
    // Directory should now be empty
    !error_happened && remove_dir(p)
}

830
/// Removes a directory at the specified path
831
pub fn remove_dir(p: &Path) -> bool {
B
Brian Anderson 已提交
832
   return rmdir(p);
833

834
    #[cfg(windows)]
835
    fn rmdir(p: &Path) -> bool {
836
        #[fixed_stack_segment]; #[inline(never)];
837 838
        unsafe {
            use os::win32::as_utf16_p;
839
            return do as_utf16_p(p.as_str().unwrap()) |buf| {
840 841 842
                libc::RemoveDirectoryW(buf) != (0 as libc::BOOL)
            };
        }
843 844
    }

845
    #[cfg(unix)]
846
    fn rmdir(p: &Path) -> bool {
847
        #[fixed_stack_segment]; #[inline(never)];
K
Kevin Ballard 已提交
848
        do p.with_c_str |buf| {
E
Erick Tryzelaar 已提交
849
            unsafe {
850
                libc::rmdir(buf) == (0 as c_int)
E
Erick Tryzelaar 已提交
851
            }
852
        }
853 854 855
    }
}

856 857
/// Changes the current working directory to the specified path, returning
/// whether the change was completed successfully or not.
858
pub fn change_dir(p: &Path) -> bool {
B
Brian Anderson 已提交
859
    return chdir(p);
860

861
    #[cfg(windows)]
862
    fn chdir(p: &Path) -> bool {
863
        #[fixed_stack_segment]; #[inline(never)];
864 865
        unsafe {
            use os::win32::as_utf16_p;
866
            return do as_utf16_p(p.as_str().unwrap()) |buf| {
867 868 869
                libc::SetCurrentDirectoryW(buf) != (0 as libc::BOOL)
            };
        }
870 871
    }

872
    #[cfg(unix)]
873
    fn chdir(p: &Path) -> bool {
874
        #[fixed_stack_segment]; #[inline(never)];
K
Kevin Ballard 已提交
875
        do p.with_c_str |buf| {
E
Erick Tryzelaar 已提交
876
            unsafe {
877
                libc::chdir(buf) == (0 as c_int)
E
Erick Tryzelaar 已提交
878
            }
879
        }
880 881 882
    }
}

883
/// Copies a file from one location to another
884
pub fn copy_file(from: &Path, to: &Path) -> bool {
B
Brian Anderson 已提交
885
    return do_copy_file(from, to);
886

887
    #[cfg(windows)]
888
    fn do_copy_file(from: &Path, to: &Path) -> bool {
889
        #[fixed_stack_segment]; #[inline(never)];
890 891
        unsafe {
            use os::win32::as_utf16_p;
892 893
            return do as_utf16_p(from.as_str().unwrap()) |fromp| {
                do as_utf16_p(to.as_str().unwrap()) |top| {
894 895 896
                    libc::CopyFileW(fromp, top, (0 as libc::BOOL)) !=
                        (0 as libc::BOOL)
                }
897 898 899 900
            }
        }
    }

901
    #[cfg(unix)]
902
    fn do_copy_file(from: &Path, to: &Path) -> bool {
903
        #[fixed_stack_segment]; #[inline(never)];
904
        unsafe {
K
Kevin Ballard 已提交
905 906
            let istream = do from.with_c_str |fromp| {
                do "rb".with_c_str |modebuf| {
907 908 909 910 911
                    libc::fopen(fromp, modebuf)
                }
            };
            if istream as uint == 0u {
                return false;
912
            }
913 914 915 916
            // Preserve permissions
            let from_mode = from.get_mode().expect("copy_file: couldn't get permissions \
                                                    for source file");

K
Kevin Ballard 已提交
917 918
            let ostream = do to.with_c_str |top| {
                do "w+b".with_c_str |modebuf| {
919 920 921 922 923 924
                    libc::fopen(top, modebuf)
                }
            };
            if ostream as uint == 0u {
                fclose(istream);
                return false;
925
            }
926 927 928 929 930
            let bufsize = 8192u;
            let mut buf = vec::with_capacity::<u8>(bufsize);
            let mut done = false;
            let mut ok = true;
            while !done {
931
                do buf.as_mut_buf |b, _sz| {
932 933 934 935 936 937 938 939 940 941
                  let nread = libc::fread(b as *mut c_void, 1u as size_t,
                                          bufsize as size_t,
                                          istream);
                  if nread > 0 as size_t {
                      if libc::fwrite(b as *c_void, 1u as size_t, nread,
                                      ostream) != nread {
                          ok = false;
                          done = true;
                      }
                  } else {
942 943
                      done = true;
                  }
944
              }
945 946 947
            }
            fclose(istream);
            fclose(ostream);
948 949

            // Give the new file the old file's permissions
K
Kevin Ballard 已提交
950
            if do to.with_c_str |to_buf| {
951
                libc::chmod(to_buf, from_mode as libc::mode_t)
J
James Miller 已提交
952 953
            } != 0 {
                return false; // should be a condition...
954
            }
955
            return ok;
956 957 958 959
        }
    }
}

960
/// Deletes an existing file
961
pub fn remove_file(p: &Path) -> bool {
B
Brian Anderson 已提交
962
    return unlink(p);
963

964
    #[cfg(windows)]
965
    fn unlink(p: &Path) -> bool {
966
        #[fixed_stack_segment]; #[inline(never)];
967 968
        unsafe {
            use os::win32::as_utf16_p;
969
            return do as_utf16_p(p.as_str().unwrap()) |buf| {
970 971 972
                libc::DeleteFileW(buf) != (0 as libc::BOOL)
            };
        }
973 974
    }

975
    #[cfg(unix)]
976
    fn unlink(p: &Path) -> bool {
977
        #[fixed_stack_segment]; #[inline(never)];
978
        unsafe {
K
Kevin Ballard 已提交
979
            do p.with_c_str |buf| {
980
                libc::unlink(buf) == (0 as c_int)
E
Erick Tryzelaar 已提交
981
            }
982
        }
983 984 985
    }
}

986 987 988 989 990 991 992 993 994 995 996 997
/// Renames an existing file or directory
pub fn rename_file(old: &Path, new: &Path) -> bool {
    #[fixed_stack_segment]; #[inline(never)];
    unsafe {
       do old.with_c_str |old_buf| {
            do new.with_c_str |new_buf| {
                libc::rename(old_buf, new_buf) == (0 as c_int)
            }
       }
    }
}

998
#[cfg(unix)]
999
/// Returns the platform-specific value of errno
1000 1001 1002 1003
pub fn errno() -> int {
    #[cfg(target_os = "macos")]
    #[cfg(target_os = "freebsd")]
    fn errno_location() -> *c_int {
1004
        #[fixed_stack_segment]; #[inline(never)];
1005 1006
        #[nolink]
        extern {
1007
            fn __error() -> *c_int;
1008 1009 1010 1011 1012 1013 1014 1015 1016
        }
        unsafe {
            __error()
        }
    }

    #[cfg(target_os = "linux")]
    #[cfg(target_os = "android")]
    fn errno_location() -> *c_int {
1017
        #[fixed_stack_segment]; #[inline(never)];
1018 1019
        #[nolink]
        extern {
1020
            fn __errno_location() -> *c_int;
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
        }
        unsafe {
            __errno_location()
        }
    }

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

#[cfg(windows)]
1033
/// Returns the platform-specific value of errno
1034
pub fn errno() -> uint {
1035
    #[fixed_stack_segment]; #[inline(never)];
1036 1037
    use libc::types::os::arch::extra::DWORD;

K
klutzy 已提交
1038
    #[cfg(target_arch = "x86")]
1039
    #[link_name = "kernel32"]
1040
    extern "stdcall" {
1041
        fn GetLastError() -> DWORD;
1042 1043
    }

K
klutzy 已提交
1044 1045 1046 1047 1048 1049
    #[cfg(target_arch = "x86_64")]
    #[link_name = "kernel32"]
    extern {
        fn GetLastError() -> DWORD;
    }

1050
    unsafe {
1051
        GetLastError() as uint
1052 1053 1054
    }
}

1055
/// Get a string representing the platform-dependent last error
1056
pub fn last_os_error() -> ~str {
1057 1058 1059 1060 1061
    #[cfg(unix)]
    fn strerror() -> ~str {
        #[cfg(target_os = "macos")]
        #[cfg(target_os = "android")]
        #[cfg(target_os = "freebsd")]
1062 1063
        fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: size_t)
                      -> c_int {
1064 1065
            #[fixed_stack_segment]; #[inline(never)];

1066 1067
            #[nolink]
            extern {
1068 1069
                fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: size_t)
                              -> c_int;
1070 1071 1072 1073 1074 1075 1076 1077
            }
            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 已提交
1078
        // So we just use __xpg_strerror_r which is always POSIX compliant
1079
        #[cfg(target_os = "linux")]
1080
        fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: size_t) -> c_int {
1081
            #[fixed_stack_segment]; #[inline(never)];
1082 1083
            #[nolink]
            extern {
1084 1085 1086 1087
                fn __xpg_strerror_r(errnum: c_int,
                                    buf: *mut c_char,
                                    buflen: size_t)
                                    -> c_int;
1088 1089 1090 1091 1092 1093 1094
            }
            unsafe {
                __xpg_strerror_r(errnum, buf, buflen)
            }
        }

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

1096 1097 1098
        do buf.as_mut_buf |buf, len| {
            unsafe {
                if strerror_r(errno() as c_int, buf, len as size_t) < 0 {
A
Alex Crichton 已提交
1099
                    fail2!("strerror_r failure");
1100 1101 1102 1103
                }

                str::raw::from_c_str(buf as *c_char)
            }
1104
        }
1105
    }
1106 1107 1108

    #[cfg(windows)]
    fn strerror() -> ~str {
1109 1110
        #[fixed_stack_segment]; #[inline(never)];

1111
        use libc::types::os::arch::extra::DWORD;
1112
        use libc::types::os::arch::extra::LPWSTR;
1113
        use libc::types::os::arch::extra::LPVOID;
1114
        use libc::types::os::arch::extra::WCHAR;
1115

K
klutzy 已提交
1116
        #[cfg(target_arch = "x86")]
1117
        #[link_name = "kernel32"]
1118
        extern "stdcall" {
1119
            fn FormatMessageW(flags: DWORD,
1120 1121 1122
                              lpSrc: LPVOID,
                              msgId: DWORD,
                              langId: DWORD,
1123
                              buf: LPWSTR,
1124 1125 1126
                              nsize: DWORD,
                              args: *c_void)
                              -> DWORD;
1127 1128
        }

K
klutzy 已提交
1129 1130 1131
        #[cfg(target_arch = "x86_64")]
        #[link_name = "kernel32"]
        extern {
1132
            fn FormatMessageW(flags: DWORD,
K
klutzy 已提交
1133 1134 1135
                              lpSrc: LPVOID,
                              msgId: DWORD,
                              langId: DWORD,
1136
                              buf: LPWSTR,
K
klutzy 已提交
1137 1138 1139 1140 1141
                              nsize: DWORD,
                              args: *c_void)
                              -> DWORD;
        }

1142 1143
        static FORMAT_MESSAGE_FROM_SYSTEM: DWORD = 0x00001000;
        static FORMAT_MESSAGE_IGNORE_INSERTS: DWORD = 0x00000200;
1144 1145 1146 1147 1148 1149

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

1150
        let mut buf = [0 as WCHAR, ..TMPBUF_SZ];
1151

1152
        unsafe {
1153
            do buf.as_mut_buf |buf, len| {
1154
                let res = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
1155 1156 1157 1158 1159 1160 1161 1162
                                         FORMAT_MESSAGE_IGNORE_INSERTS,
                                         ptr::mut_null(),
                                         err,
                                         langId,
                                         buf,
                                         len as DWORD,
                                         ptr::null());
                if res == 0 {
A
Alex Crichton 已提交
1163
                    fail2!("[{}] FormatMessage failure", errno());
1164
                }
1165 1166
            }

1167
            str::from_utf16(buf)
1168 1169 1170 1171
        }
    }

    strerror()
1172
}
1173

1174 1175 1176 1177 1178 1179 1180 1181
/**
 * 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
 * ignored and the process exits with the default failure status
 */
1182
pub fn set_exit_status(code: int) {
1183
    use rt;
1184
    rt::set_exit_status(code);
1185
}
1186

1187 1188
unsafe fn load_argc_and_argv(argc: c_int, argv: **c_char) -> ~[~str] {
    let mut args = ~[];
D
Daniel Micay 已提交
1189
    for i in range(0u, argc as uint) {
1190
        args.push(str::raw::from_c_str(*argv.offset(i as int)));
1191
    }
L
Luqman Aden 已提交
1192
    args
1193 1194
}

1195 1196 1197 1198 1199 1200
/**
 * Returns the command line arguments
 *
 * Returns a list of the command line arguments.
 */
#[cfg(target_os = "macos")]
1201
fn real_args() -> ~[~str] {
1202 1203
    #[fixed_stack_segment]; #[inline(never)];

1204
    unsafe {
1205 1206 1207
        let (argc, argv) = (*_NSGetArgc() as c_int,
                            *_NSGetArgv() as **c_char);
        load_argc_and_argv(argc, argv)
1208 1209 1210
    }
}

1211
#[cfg(target_os = "linux")]
K
kyeongwoon 已提交
1212
#[cfg(target_os = "android")]
1213
#[cfg(target_os = "freebsd")]
1214
fn real_args() -> ~[~str] {
1215 1216
    use rt;

1217 1218
    match rt::args::clone() {
        Some(args) => args,
A
Alex Crichton 已提交
1219
        None => fail2!("process arguments not initialized")
1220
    }
1221 1222
}

1223
#[cfg(windows)]
1224
fn real_args() -> ~[~str] {
1225 1226
    #[fixed_stack_segment]; #[inline(never)];

1227
    let mut nArgs: c_int = 0;
D
Daniel Micay 已提交
1228
    let lpArgCount: *mut c_int = &mut nArgs;
T
Tim Chevalier 已提交
1229 1230
    let lpCmdLine = unsafe { GetCommandLineW() };
    let szArgList = unsafe { CommandLineToArgvW(lpCmdLine, lpArgCount) };
1231 1232

    let mut args = ~[];
D
Daniel Micay 已提交
1233
    for i in range(0u, nArgs as uint) {
1234 1235
        unsafe {
            // Determine the length of this argument.
1236
            let ptr = *szArgList.offset(i as int);
1237
            let mut len = 0;
1238
            while *ptr.offset(len as int) != 0 { len += 1; }
1239 1240

            // Push it onto the list.
1241
            args.push(vec::raw::buf_as_slice(ptr, len,
1242
                                             str::from_utf16));
1243 1244 1245 1246
        }
    }

    unsafe {
1247
        LocalFree(szArgList as *c_void);
1248 1249 1250 1251 1252 1253 1254
    }

    return args;
}

type LPCWSTR = *u16;

K
klutzy 已提交
1255
#[cfg(windows, target_arch = "x86")]
1256 1257
#[link_name="kernel32"]
#[abi="stdcall"]
1258
extern "stdcall" {
1259 1260 1261 1262
    fn GetCommandLineW() -> LPCWSTR;
    fn LocalFree(ptr: *c_void);
}

K
klutzy 已提交
1263 1264 1265 1266 1267 1268 1269 1270
#[cfg(windows, target_arch = "x86_64")]
#[link_name="kernel32"]
extern {
    fn GetCommandLineW() -> LPCWSTR;
    fn LocalFree(ptr: *c_void);
}

#[cfg(windows, target_arch = "x86")]
1271 1272
#[link_name="shell32"]
#[abi="stdcall"]
1273
extern "stdcall" {
1274
    fn CommandLineToArgvW(lpCmdLine: LPCWSTR, pNumArgs: *mut c_int) -> **u16;
1275 1276
}

K
klutzy 已提交
1277 1278 1279 1280 1281 1282
#[cfg(windows, target_arch = "x86_64")]
#[link_name="shell32"]
extern {
    fn CommandLineToArgvW(lpCmdLine: LPCWSTR, pNumArgs: *mut c_int) -> **u16;
}

1283 1284 1285 1286
struct OverriddenArgs {
    val: ~[~str]
}

1287 1288
/// Returns the arguments which this program was started with (normally passed
/// via the command line).
1289
pub fn args() -> ~[~str] {
1290
    real_args()
1291 1292
}

1293 1294 1295 1296 1297 1298 1299
#[cfg(target_os = "macos")]
extern {
    // These functions are in crt_externs.h.
    pub fn _NSGetArgc() -> *c_int;
    pub fn _NSGetArgv() -> ***c_char;
}

1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
// 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
    }
}

#[cfg(unix)]
pub fn page_size() -> uint {
1316 1317
    #[fixed_stack_segment]; #[inline(never)];

1318 1319 1320 1321 1322 1323 1324
    unsafe {
        libc::sysconf(libc::_SC_PAGESIZE) as uint
    }
}

#[cfg(windows)]
pub fn page_size() -> uint {
1325 1326
    #[fixed_stack_segment]; #[inline(never)];

V
Vadim Chugunov 已提交
1327 1328 1329
    unsafe {
        let mut info = libc::SYSTEM_INFO::new();
        libc::GetSystemInfo(&mut info);
1330

V
Vadim Chugunov 已提交
1331 1332
        return info.dwPageSize as uint;
    }
1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381
}

pub struct MemoryMap {
    data: *mut u8,
    len: size_t,
    kind: MemoryMapKind
}

pub enum MemoryMapKind {
    MapFile(*c_void),
    MapVirtual
}

pub enum MapOption {
    MapReadable,
    MapWritable,
    MapExecutable,
    MapAddr(*c_void),
    MapFd(c_int),
    MapOffset(uint)
}

pub enum MapError {
    // Linux-specific errors
    ErrFdNotAvail,
    ErrInvalidFd,
    ErrUnaligned,
    ErrNoMapSupport,
    ErrNoMem,
    ErrUnknown(libc::c_int),

    // Windows-specific errors
    ErrUnsupProt,
    ErrUnsupOffset,
    ErrAlreadyExists,
    ErrVirtualAlloc(uint),
    ErrCreateFileMappingW(uint),
    ErrMapViewOfFile(uint)
}

impl to_str::ToStr for MapError {
    fn to_str(&self) -> ~str {
        match *self {
            ErrFdNotAvail => ~"fd not available for reading or writing",
            ErrInvalidFd => ~"Invalid fd",
            ErrUnaligned => ~"Unaligned address, invalid flags, \
                              negative length or unaligned offset",
            ErrNoMapSupport=> ~"File doesn't support mapping",
            ErrNoMem => ~"Invalid address, or not enough available memory",
A
Alex Crichton 已提交
1382
            ErrUnknown(code) => format!("Unknown error={}", code),
1383 1384 1385
            ErrUnsupProt => ~"Protection mode unsupported",
            ErrUnsupOffset => ~"Offset in virtual memory mode is unsupported",
            ErrAlreadyExists => ~"File mapping for specified file already exists",
A
Alex Crichton 已提交
1386 1387 1388
            ErrVirtualAlloc(code) => format!("VirtualAlloc failure={}", code),
            ErrCreateFileMappingW(code) => format!("CreateFileMappingW failure={}", code),
            ErrMapViewOfFile(code) => format!("MapViewOfFile failure={}", code)
1389 1390 1391 1392 1393 1394
        }
    }
}

#[cfg(unix)]
impl MemoryMap {
1395
    pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
1396 1397
        #[fixed_stack_segment]; #[inline(never)];

1398 1399 1400 1401 1402 1403 1404 1405 1406
        use libc::off_t;

        let mut addr: *c_void = ptr::null();
        let mut prot: c_int = 0;
        let mut flags: c_int = libc::MAP_PRIVATE;
        let mut fd: c_int = -1;
        let mut offset: off_t = 0;
        let len = round_up(min_len, page_size()) as size_t;

D
Daniel Micay 已提交
1407
        for &o in options.iter() {
1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
            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_;
                },
                MapOffset(offset_) => { offset = offset_ as off_t; }
            }
        }
        if fd == -1 { flags |= libc::MAP_ANON; }

        let r = unsafe {
            libc::mmap(addr, len, prot, flags, fd, offset)
        };
1428
        if r.equiv(&libc::MAP_FAILED) {
1429 1430 1431 1432 1433 1434 1435 1436 1437
            Err(match errno() as c_int {
                libc::EACCES => ErrFdNotAvail,
                libc::EBADF => ErrInvalidFd,
                libc::EINVAL => ErrUnaligned,
                libc::ENODEV => ErrNoMapSupport,
                libc::ENOMEM => ErrNoMem,
                code => ErrUnknown(code)
            })
        } else {
1438
            Ok(MemoryMap {
1439 1440 1441 1442 1443 1444 1445 1446 1447 1448
               data: r as *mut u8,
               len: len,
               kind: if fd == -1 {
                   MapVirtual
               } else {
                   MapFile(ptr::null())
               }
            })
        }
    }
V
Vadim Chugunov 已提交
1449 1450 1451 1452

    pub fn granularity() -> uint {
        page_size()
    }
1453 1454 1455 1456
}

#[cfg(unix)]
impl Drop for MemoryMap {
D
Daniel Micay 已提交
1457
    fn drop(&mut self) {
1458 1459
        #[fixed_stack_segment]; #[inline(never)];

1460 1461 1462
        unsafe {
            match libc::munmap(self.data as *c_void, self.len) {
                0 => (),
A
Alex Crichton 已提交
1463 1464 1465 1466 1467
                -1 => match errno() as c_int {
                    libc::EINVAL => error2!("invalid addr or len"),
                    e => error2!("unknown errno={}", e)
                },
                r => error2!("Unexpected result {}", r)
1468 1469 1470 1471 1472 1473 1474
            }
        }
    }
}

#[cfg(windows)]
impl MemoryMap {
1475
    pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
1476 1477
        #[fixed_stack_segment]; #[inline(never)];

1478 1479 1480 1481 1482 1483 1484 1485 1486 1487
        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;
        let len = round_up(min_len, page_size()) as SIZE_T;

D
Daniel Micay 已提交
1488
        for &o in options.iter() {
1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520
            match o {
                MapReadable => { readable = true; },
                MapWritable => { writable = true; },
                MapExecutable => { executable = true; }
                MapAddr(addr_) => { lpAddress = addr_ as LPVOID; },
                MapFd(fd_) => { fd = fd_; },
                MapOffset(offset_) => { offset = offset_; }
            }
        }

        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,
                                   len,
                                   libc::MEM_COMMIT | libc::MEM_RESERVE,
                                   flProtect)
            };
            match r as uint {
                0 => Err(ErrVirtualAlloc(errno())),
1521
                _ => Ok(MemoryMap {
1522 1523 1524 1525 1526 1527
                   data: r as *mut u8,
                   len: len,
                   kind: MapVirtual
                })
            }
        } else {
V
Vadim Chugunov 已提交
1528 1529 1530 1531 1532 1533 1534
            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.
1535 1536 1537 1538 1539 1540
            };
            unsafe {
                let hFile = libc::get_osfhandle(fd) as HANDLE;
                let mapping = libc::CreateFileMappingW(hFile,
                                                       ptr::mut_null(),
                                                       flProtect,
V
Vadim Chugunov 已提交
1541 1542
                                                       0,
                                                       0,
1543 1544 1545 1546 1547 1548 1549 1550 1551
                                                       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 已提交
1552
                                            ((len as u64) >> 32) as DWORD,
1553 1554 1555 1556
                                            (offset & 0xffff_ffff) as DWORD,
                                            0);
                match r as uint {
                    0 => Err(ErrMapViewOfFile(errno())),
1557
                    _ => Ok(MemoryMap {
1558 1559 1560 1561 1562 1563 1564 1565
                       data: r as *mut u8,
                       len: len,
                       kind: MapFile(mapping as *c_void)
                    })
                }
            }
        }
    }
V
Vadim Chugunov 已提交
1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578

    /// Granularity of MapAddr() and MapOffset() parameter values.
    /// This may be greater than the value returned by page_size().
    pub fn granularity() -> uint {
        #[fixed_stack_segment]; #[inline(never)];

        unsafe {
            let mut info = libc::SYSTEM_INFO::new();
            libc::GetSystemInfo(&mut info);

            return info.dwAllocationGranularity as uint;
        }
    }
1579 1580 1581 1582
}

#[cfg(windows)]
impl Drop for MemoryMap {
D
Daniel Micay 已提交
1583
    fn drop(&mut self) {
1584 1585
        #[fixed_stack_segment]; #[inline(never)];

1586
        use libc::types::os::arch::extra::{LPCVOID, HANDLE};
V
Vadim Chugunov 已提交
1587
        use libc::consts::os::extra::FALSE;
1588 1589 1590

        unsafe {
            match self.kind {
V
Vadim Chugunov 已提交
1591 1592 1593 1594
                MapVirtual => {
                    if libc::VirtualFree(self.data as *mut c_void,
                                         self.len,
                                         libc::MEM_RELEASE) == FALSE {
A
Alex Crichton 已提交
1595
                        error2!("VirtualFree failed: {}", errno());
V
Vadim Chugunov 已提交
1596
                    }
1597 1598
                },
                MapFile(mapping) => {
V
Vadim Chugunov 已提交
1599
                    if libc::UnmapViewOfFile(self.data as LPCVOID) == FALSE {
A
Alex Crichton 已提交
1600
                        error2!("UnmapViewOfFile failed: {}", errno());
1601
                    }
V
Vadim Chugunov 已提交
1602
                    if libc::CloseHandle(mapping as HANDLE) == FALSE {
A
Alex Crichton 已提交
1603
                        error2!("CloseHandle failed: {}", errno());
1604 1605 1606 1607 1608 1609 1610
                    }
                }
            }
        }
    }
}

1611
pub mod consts {
1612

I
ILyoan 已提交
1613
    #[cfg(unix)]
1614
    pub use os::consts::unix::*;
1615

I
ILyoan 已提交
1616
    #[cfg(windows)]
1617
    pub use os::consts::windows::*;
1618

I
ILyoan 已提交
1619
    #[cfg(target_os = "macos")]
1620
    pub use os::consts::macos::*;
I
ILyoan 已提交
1621 1622

    #[cfg(target_os = "freebsd")]
1623
    pub use os::consts::freebsd::*;
I
ILyoan 已提交
1624 1625

    #[cfg(target_os = "linux")]
1626
    pub use os::consts::linux::*;
I
ILyoan 已提交
1627

K
kyeongwoon 已提交
1628
    #[cfg(target_os = "android")]
1629
    pub use os::consts::android::*;
K
kyeongwoon 已提交
1630

I
ILyoan 已提交
1631
    #[cfg(target_os = "win32")]
1632
    pub use os::consts::win32::*;
1633

1634 1635 1636 1637 1638 1639 1640 1641 1642 1643
    #[cfg(target_arch = "x86")]
    pub use os::consts::x86::*;

    #[cfg(target_arch = "x86_64")]
    pub use os::consts::x86_64::*;

    #[cfg(target_arch = "arm")]
    pub use os::consts::arm::*;

    #[cfg(target_arch = "mips")]
1644
    pub use os::consts::mips::*;
1645 1646 1647 1648 1649 1650 1651 1652 1653

    pub mod unix {
        pub static FAMILY: &'static str = "unix";
    }

    pub mod windows {
        pub static FAMILY: &'static str = "windows";
    }

I
ILyoan 已提交
1654
    pub mod macos {
1655 1656 1657
        pub static SYSNAME: &'static str = "macos";
        pub static DLL_PREFIX: &'static str = "lib";
        pub static DLL_SUFFIX: &'static str = ".dylib";
1658
        pub static DLL_EXTENSION: &'static str = "dylib";
1659
        pub static EXE_SUFFIX: &'static str = "";
1660
        pub static EXE_EXTENSION: &'static str = "";
I
ILyoan 已提交
1661 1662 1663
    }

    pub mod freebsd {
1664 1665 1666
        pub static SYSNAME: &'static str = "freebsd";
        pub static DLL_PREFIX: &'static str = "lib";
        pub static DLL_SUFFIX: &'static str = ".so";
1667
        pub static DLL_EXTENSION: &'static str = "so";
1668
        pub static EXE_SUFFIX: &'static str = "";
1669
        pub static EXE_EXTENSION: &'static str = "";
I
ILyoan 已提交
1670 1671 1672
    }

    pub mod linux {
1673 1674 1675
        pub static SYSNAME: &'static str = "linux";
        pub static DLL_PREFIX: &'static str = "lib";
        pub static DLL_SUFFIX: &'static str = ".so";
1676
        pub static DLL_EXTENSION: &'static str = "so";
1677
        pub static EXE_SUFFIX: &'static str = "";
1678
        pub static EXE_EXTENSION: &'static str = "";
I
ILyoan 已提交
1679
    }
K
kyeongwoon 已提交
1680 1681

    pub mod android {
1682 1683 1684
        pub static SYSNAME: &'static str = "android";
        pub static DLL_PREFIX: &'static str = "lib";
        pub static DLL_SUFFIX: &'static str = ".so";
1685
        pub static DLL_EXTENSION: &'static str = "so";
1686
        pub static EXE_SUFFIX: &'static str = "";
1687
        pub static EXE_EXTENSION: &'static str = "";
K
kyeongwoon 已提交
1688
    }
1689

I
ILyoan 已提交
1690
    pub mod win32 {
1691 1692 1693
        pub static SYSNAME: &'static str = "win32";
        pub static DLL_PREFIX: &'static str = "";
        pub static DLL_SUFFIX: &'static str = ".dll";
1694
        pub static DLL_EXTENSION: &'static str = "dll";
1695
        pub static EXE_SUFFIX: &'static str = ".exe";
1696
        pub static EXE_EXTENSION: &'static str = "exe";
I
ILyoan 已提交
1697 1698 1699 1700
    }


    pub mod x86 {
1701
        pub static ARCH: &'static str = "x86";
I
ILyoan 已提交
1702 1703
    }
    pub mod x86_64 {
1704
        pub static ARCH: &'static str = "x86_64";
I
ILyoan 已提交
1705 1706
    }
    pub mod arm {
1707
        pub static ARCH: &'static str = "arm";
I
ILyoan 已提交
1708
    }
J
Jyun-Yan You 已提交
1709
    pub mod mips {
1710
        pub static ARCH: &'static str = "mips";
J
Jyun-Yan You 已提交
1711
    }
I
ILyoan 已提交
1712
}
1713 1714 1715

#[cfg(test)]
mod tests {
1716
    use c_str::ToCStr;
1717
    use libc::{c_int, c_void, size_t};
1718
    use libc;
A
Alex Crichton 已提交
1719
    use option::Some;
1720
    use option;
1721
    use os::{env, getcwd, getenv, make_absolute, args};
C
Corey Richardson 已提交
1722
    use os::{remove_file, setenv, unsetenv};
1723
    use os;
1724
    use path::Path;
1725
    use rand::Rng;
1726 1727
    use rand;
    use run;
1728
    use str::StrSlice;
1729 1730
    use libc::consts::os::posix88::{S_IRUSR, S_IWUSR, S_IXUSR};

1731

1732
    #[test]
1733
    pub fn last_os_error() {
A
Alex Crichton 已提交
1734
        debug2!("{}", os::last_os_error());
1735
    }
1736

1737 1738
    #[test]
    pub fn test_args() {
1739
        let a = args();
P
Patrick Walton 已提交
1740
        assert!(a.len() >= 1);
1741 1742
    }

1743
    fn make_rand_name() -> ~str {
P
Patrick Walton 已提交
1744
        let mut rng = rand::rng();
1745
        let n = ~"TEST" + rng.gen_ascii_str(10u);
P
Patrick Walton 已提交
1746
        assert!(getenv(n).is_none());
L
Luqman Aden 已提交
1747
        n
1748 1749 1750 1751 1752
    }

    #[test]
    fn test_setenv() {
        let n = make_rand_name();
E
Erick Tryzelaar 已提交
1753
        setenv(n, "VALUE");
1754
        assert_eq!(getenv(n), option::Some(~"VALUE"));
1755 1756
    }

C
Corey Richardson 已提交
1757 1758 1759
    #[test]
    fn test_unsetenv() {
        let n = make_rand_name();
E
Erick Tryzelaar 已提交
1760
        setenv(n, "VALUE");
C
Corey Richardson 已提交
1761
        unsetenv(n);
1762
        assert_eq!(getenv(n), option::None);
C
Corey Richardson 已提交
1763 1764
    }

1765
    #[test]
1766
    #[ignore]
1767 1768
    fn test_setenv_overwrite() {
        let n = make_rand_name();
E
Erick Tryzelaar 已提交
1769 1770
        setenv(n, "1");
        setenv(n, "2");
1771
        assert_eq!(getenv(n), option::Some(~"2"));
E
Erick Tryzelaar 已提交
1772
        setenv(n, "");
1773
        assert_eq!(getenv(n), option::Some(~""));
1774 1775 1776 1777 1778
    }

    // Windows GetEnvironmentVariable requires some extra work to make sure
    // the buffer the variable is copied into is the right size
    #[test]
1779
    #[ignore]
1780
    fn test_getenv_big() {
1781
        let mut s = ~"";
1782
        let mut i = 0;
1783 1784 1785 1786
        while i < 100 {
            s = s + "aaaaaaaaaa";
            i += 1;
        }
1787 1788
        let n = make_rand_name();
        setenv(n, s);
A
Alex Crichton 已提交
1789
        debug2!("{}", s.clone());
1790
        assert_eq!(getenv(n), option::Some(s));
1791 1792 1793 1794 1795
    }

    #[test]
    fn test_self_exe_path() {
        let path = os::self_exe_path();
P
Patrick Walton 已提交
1796
        assert!(path.is_some());
1797
        let path = path.unwrap();
A
Alex Crichton 已提交
1798
        debug2!("{:?}", path.clone());
1799 1800

        // Hard to test this function
1801
        assert!(path.is_absolute());
1802 1803 1804
    }

    #[test]
1805
    #[ignore]
1806 1807
    fn test_env_getenv() {
        let e = env();
Y
Youngmin Yoo 已提交
1808
        assert!(e.len() > 0u);
D
Daniel Micay 已提交
1809
        for p in e.iter() {
1810
            let (n, v) = (*p).clone();
A
Alex Crichton 已提交
1811
            debug2!("{:?}", n.clone());
1812 1813 1814 1815
            let v2 = getenv(n);
            // 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 已提交
1816
            assert!(v2.is_none() || v2 == option::Some(v));
1817 1818 1819 1820 1821 1822 1823
        }
    }

    #[test]
    fn test_env_setenv() {
        let n = make_rand_name();

1824
        let mut e = env();
E
Erick Tryzelaar 已提交
1825
        setenv(n, "VALUE");
1826
        assert!(!e.contains(&(n.clone(), ~"VALUE")));
1827 1828

        e = env();
1829
        assert!(e.contains(&(n, ~"VALUE")));
1830 1831
    }

1832 1833
    #[test]
    fn test() {
1834
        assert!((!Path::new("test-path").is_absolute()));
1835

1836 1837
        let cwd = getcwd();
        debug2!("Current working directory: {}", cwd.display());
1838

1839 1840
        debug2!("{:?}", make_absolute(&Path::new("test-path")));
        debug2!("{:?}", make_absolute(&Path::new("/usr/bin")));
1841 1842 1843
    }

    #[test]
1844
    #[cfg(unix)]
1845
    fn homedir() {
E
Erick Tryzelaar 已提交
1846
        let oldhome = getenv("HOME");
1847

E
Erick Tryzelaar 已提交
1848
        setenv("HOME", "/home/MountainView");
1849
        assert_eq!(os::homedir(), Some(Path::new("/home/MountainView")));
1850

E
Erick Tryzelaar 已提交
1851
        setenv("HOME", "");
P
Patrick Walton 已提交
1852
        assert!(os::homedir().is_none());
1853

D
Daniel Micay 已提交
1854
        for s in oldhome.iter() { setenv("HOME", *s) }
1855 1856 1857
    }

    #[test]
1858
    #[cfg(windows)]
1859 1860
    fn homedir() {

E
Erick Tryzelaar 已提交
1861 1862
        let oldhome = getenv("HOME");
        let olduserprofile = getenv("USERPROFILE");
1863

E
Erick Tryzelaar 已提交
1864 1865
        setenv("HOME", "");
        setenv("USERPROFILE", "");
1866

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

E
Erick Tryzelaar 已提交
1869
        setenv("HOME", "/home/MountainView");
1870
        assert_eq!(os::homedir(), Some(Path::new("/home/MountainView")));
1871

E
Erick Tryzelaar 已提交
1872
        setenv("HOME", "");
1873

E
Erick Tryzelaar 已提交
1874
        setenv("USERPROFILE", "/home/MountainView");
1875
        assert_eq!(os::homedir(), Some(Path::new("/home/MountainView")));
1876

E
Erick Tryzelaar 已提交
1877 1878
        setenv("HOME", "/home/MountainView");
        setenv("USERPROFILE", "/home/PaloAlto");
1879
        assert_eq!(os::homedir(), Some(Path::new("/home/MountainView")));
1880

1881 1882
        for s in oldhome.iter() { setenv("HOME", *s) }
        for s in olduserprofile.iter() { setenv("USERPROFILE", *s) }
1883 1884
    }

1885 1886
    #[test]
    fn tmpdir() {
1887 1888 1889
        let p = os::tmpdir();
        let s = p.as_str();
        assert!(s.is_some() && s.unwrap() != ".");
1890 1891
    }

1892 1893
    // Issue #712
    #[test]
1894
    fn test_list_dir_no_invalid_memory_access() {
1895
        os::list_dir(&Path::new("."));
1896
    }
1897 1898 1899

    #[test]
    fn list_dir() {
1900
        let dirs = os::list_dir(&Path::new("."));
1901
        // Just assuming that we've got some contents in the current directory
Y
Youngmin Yoo 已提交
1902
        assert!(dirs.len() > 0u);
1903

D
Daniel Micay 已提交
1904
        for dir in dirs.iter() {
A
Alex Crichton 已提交
1905
            debug2!("{:?}", (*dir).clone());
1906
        }
1907 1908
    }

1909 1910 1911
    #[test]
    #[cfg(not(windows))]
    fn list_dir_root() {
1912
        let dirs = os::list_dir(&Path::new("/"));
1913 1914 1915 1916 1917
        assert!(dirs.len() > 1);
    }
    #[test]
    #[cfg(windows)]
    fn list_dir_root() {
1918
        let dirs = os::list_dir(&Path::new("C:\\"));
1919 1920 1921 1922
        assert!(dirs.len() > 1);
    }


1923 1924
    #[test]
    fn path_is_dir() {
1925 1926
        assert!((os::path_is_dir(&Path::new("."))));
        assert!((!os::path_is_dir(&Path::new("test/stdtest/fs.rs"))));
1927 1928 1929 1930
    }

    #[test]
    fn path_exists() {
1931 1932
        assert!((os::path_exists(&Path::new("."))));
        assert!((!os::path_exists(&Path::new(
P
Patrick Walton 已提交
1933
                     "test/nonexistent-bogus-path"))));
1934 1935
    }

1936 1937
    #[test]
    fn copy_file_does_not_exist() {
1938 1939 1940
      assert!(!os::copy_file(&Path::new("test/nonexistent-bogus-path"),
                            &Path::new("test/other-bogus-path")));
      assert!(!os::path_exists(&Path::new("test/other-bogus-path")));
1941 1942 1943 1944
    }

    #[test]
    fn copy_file_ok() {
1945 1946
        #[fixed_stack_segment]; #[inline(never)];

1947
        unsafe {
E
Erick Tryzelaar 已提交
1948 1949
            let tempdir = getcwd(); // would like to use $TMPDIR,
                                    // doesn't seem to work on Linux
1950 1951
            let input = tempdir.join("in.txt");
            let out = tempdir.join("out.txt");
1952

E
Erick Tryzelaar 已提交
1953
            /* Write the temp input file */
K
Kevin Ballard 已提交
1954 1955
            let ostream = do input.with_c_str |fromp| {
                do "w+b".with_c_str |modebuf| {
1956 1957
                    libc::fopen(fromp, modebuf)
                }
E
Erick Tryzelaar 已提交
1958 1959 1960
            };
            assert!((ostream as uint != 0u));
            let s = ~"hello";
K
Kevin Ballard 已提交
1961
            do "hello".with_c_str |buf| {
1962 1963 1964 1965 1966
                let write_len = libc::fwrite(buf as *c_void,
                                             1u as size_t,
                                             (s.len() + 1u) as size_t,
                                             ostream);
                assert_eq!(write_len, (s.len() + 1) as size_t)
E
Erick Tryzelaar 已提交
1967 1968 1969 1970 1971
            }
            assert_eq!(libc::fclose(ostream), (0u as c_int));
            let in_mode = input.get_mode();
            let rs = os::copy_file(&input, &out);
            if (!os::path_exists(&input)) {
1972
                fail2!("{} doesn't exist", input.display());
E
Erick Tryzelaar 已提交
1973 1974
            }
            assert!((rs));
1975 1976 1977
            // FIXME (#9639): This needs to handle non-utf8 paths
            let rslt = run::process_status("diff", [input.as_str().unwrap().to_owned(),
                                                    out.as_str().unwrap().to_owned()]);
E
Erick Tryzelaar 已提交
1978 1979 1980 1981
            assert_eq!(rslt, 0);
            assert_eq!(out.get_mode(), in_mode);
            assert!((remove_file(&input)));
            assert!((remove_file(&out)));
1982
        }
1983
    }
1984 1985

    #[test]
1986
    fn recursive_mkdir_slash() {
1987
        let path = Path::new("/");
1988 1989
        assert!(os::mkdir_recursive(&path,  (S_IRUSR | S_IWUSR | S_IXUSR) as i32));
    }
1990

1991 1992 1993 1994
    #[test]
    fn memory_map_rw() {
        use result::{Ok, Err};

1995
        let chunk = match os::MemoryMap::new(16, [
1996 1997 1998 1999
            os::MapReadable,
            os::MapWritable
        ]) {
            Ok(chunk) => chunk,
A
Alex Crichton 已提交
2000
            Err(msg) => fail2!(msg.to_str())
2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011
        };
        assert!(chunk.len >= 16);

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

    #[test]
    fn memory_map_file() {
2012 2013
        #[fixed_stack_segment]; #[inline(never)];

2014 2015 2016 2017 2018
        use result::{Ok, Err};
        use os::*;
        use libc::*;

        #[cfg(unix)]
2019 2020
        #[fixed_stack_segment]
        #[inline(never)]
2021 2022 2023 2024 2025 2026
        fn lseek_(fd: c_int, size: uint) {
            unsafe {
                assert!(lseek(fd, size as off_t, SEEK_SET) == size as off_t);
            }
        }
        #[cfg(windows)]
2027 2028
        #[fixed_stack_segment]
        #[inline(never)]
2029 2030 2031 2032 2033 2034
        fn lseek_(fd: c_int, size: uint) {
           unsafe {
               assert!(lseek(fd, size as c_long, SEEK_SET) == size as c_long);
           }
        }

2035
        let mut path = tmpdir();
2036
        path.push("mmap_file.tmp");
V
Vadim Chugunov 已提交
2037
        let size = MemoryMap::granularity() * 2;
E
Erick Tryzelaar 已提交
2038
        remove_file(&path);
2039 2040

        let fd = unsafe {
K
Kevin Ballard 已提交
2041
            let fd = do path.with_c_str |path| {
2042 2043 2044
                open(path, O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR)
            };
            lseek_(fd, size);
K
Kevin Ballard 已提交
2045
            do "x".with_c_str |x| {
2046 2047 2048 2049
                assert!(write(fd, x as *c_void, 1) == 1);
            }
            fd
        };
2050
        let chunk = match MemoryMap::new(size / 2, [
2051 2052 2053 2054 2055 2056
            MapReadable,
            MapWritable,
            MapFd(fd),
            MapOffset(size / 2)
        ]) {
            Ok(chunk) => chunk,
A
Alex Crichton 已提交
2057
            Err(msg) => fail2!(msg.to_str())
2058 2059 2060 2061 2062 2063 2064 2065 2066 2067
        };
        assert!(chunk.len > 0);

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

2068
    // More recursive_mkdir tests are in extra::tempfile
2069
}