os.rs 59.7 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 cast;
32
use container::Container;
33
use io;
34
use iterator::IteratorUtil;
35
use libc;
A
Alex Crichton 已提交
36
use libc::{c_char, c_void, c_int, size_t};
37
use libc::FILE;
38
use local_data;
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 uint;
46
use unstable::finally::Finally;
47
use vec;
48

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

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

59 60 61 62 63 64 65 66 67 68 69
pub mod rustrt {
    use libc::{c_char, c_int};
    use libc;

    pub extern {
        unsafe fn rust_get_argc() -> c_int;
        unsafe fn rust_get_argv() -> **c_char;
        unsafe fn rust_path_is_dir(path: *libc::c_char) -> c_int;
        unsafe fn rust_path_exists(path: *libc::c_char) -> c_int;
        unsafe fn rust_set_exit_status(code: libc::intptr_t);
    }
70 71
}

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

75
pub fn getcwd() -> Path {
76
    let buf = [0 as libc::c_char, ..BUF_BYTES];
77
    unsafe {
78 79 80 81 82 83
        if(0 as *libc::c_char == libc::getcwd(
            &buf[0],
            BUF_BYTES as libc::size_t)) {
            fail!();
        }
        Path(str::raw::from_c_str(&buf[0]))
84
    }
85 86
}

87 88
// FIXME: move these to str perhaps? #2620

89
pub fn as_c_charp<T>(s: &str, f: &fn(*c_char) -> T) -> T {
B
Brian Anderson 已提交
90
    str::as_c_str(s, |b| f(b as *c_char))
91 92
}

93
pub fn fill_charp_buf(f: &fn(*mut c_char, size_t) -> bool)
B
Brian Anderson 已提交
94
    -> Option<~str> {
B
Ben Striegel 已提交
95
    let mut buf = vec::from_elem(TMPBUF_SZ, 0u8 as c_char);
96
    do buf.as_mut_buf |b, sz| {
97 98 99 100
        if f(b, sz as size_t) {
            unsafe {
                Some(str::raw::from_buf(b as *u8))
            }
101
        } else {
B
Brian Anderson 已提交
102
            None
103 104 105 106
        }
    }
}

107
#[cfg(windows)]
108
pub mod win32 {
109 110 111
    use libc;
    use vec;
    use str;
112
    use option::{None, Option};
113
    use option;
114
    use os::TMPBUF_SZ;
115
    use libc::types::os::arch::extra::DWORD;
116

117
    pub fn fill_utf16_buf_and_decode(f: &fn(*mut u16, DWORD) -> DWORD)
B
Brian Anderson 已提交
118
        -> Option<~str> {
119
        unsafe {
120
            let mut n = TMPBUF_SZ as DWORD;
121 122 123
            let mut res = None;
            let mut done = false;
            while !done {
124
                let mut k: DWORD = 0;
125
                let mut buf = vec::from_elem(n as uint, 0u16);
126
                do buf.as_mut_buf |b, _sz| {
127
                    k = f(b, TMPBUF_SZ as DWORD);
128 129 130 131 132 133 134 135 136
                    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;
                    }
137
                }
138
                if k != 0 && done {
139
                    let sub = buf.slice(0, k as uint);
140 141
                    res = option::Some(str::from_utf16(sub));
                }
142
            }
143
            return res;
144 145 146
        }
    }

147
    pub fn as_utf16_p<T>(s: &str, f: &fn(*u16) -> T) -> T {
148
        let mut t = s.to_utf16();
149
        // Null terminate before passing on.
150
        t.push(0u16);
151
        t.as_imm_buf(|buf, _len| f(buf))
152
    }
153 154
}

155 156
/*
Accessing environment variables is not generally threadsafe.
157
Serialize access through a global lock.
158 159
*/
fn with_env_lock<T>(f: &fn() -> T) -> T {
160
    use unstable::finally::Finally;
161

162
    unsafe {
163 164 165 166 167 168 169
        return do (|| {
            rust_take_env_lock();
            f()
        }).finally {
            rust_drop_env_lock();
        };
    }
170

171 172 173 174 175
    extern {
        #[fast_ffi]
        fn rust_take_env_lock();
        #[fast_ffi]
        fn rust_drop_env_lock();
176
    }
B
Ben Blum 已提交
177 178
}

179 180
/// Returns a vector of (variable, value) pairs for all the environment
/// variables of the current process.
181 182
pub fn env() -> ~[(~str,~str)] {
    unsafe {
183 184 185 186 187 188 189 190
        #[cfg(windows)]
        unsafe fn get_env_pairs() -> ~[~str] {
            use libc::funcs::extra::kernel32::{
                GetEnvironmentStringsA,
                FreeEnvironmentStringsA
            };
            let ch = GetEnvironmentStringsA();
            if (ch as uint == 0) {
M
Marvin Löbel 已提交
191
                fail!("os::env() failure getting env string from OS: %s", os::last_os_error());
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
            }
            let mut curr_ptr: uint = ch as uint;
            let mut result = ~[];
            while(*(curr_ptr as *libc::c_char) != 0 as libc::c_char) {
                let env_pair = str::raw::from_c_str(
                    curr_ptr as *libc::c_char);
                result.push(env_pair);
                curr_ptr +=
                    libc::strlen(curr_ptr as *libc::c_char) as uint
                    + 1;
            }
            FreeEnvironmentStringsA(ch);
            result
        }
        #[cfg(unix)]
        unsafe fn get_env_pairs() -> ~[~str] {
208
            extern {
209 210
                unsafe fn rust_env_pairs() -> **libc::c_char;
            }
211
            let environ = rust_env_pairs();
212
            if (environ as uint == 0) {
M
Marvin Löbel 已提交
213
                fail!("os::env() failure getting env string from OS: %s", os::last_os_error());
214 215 216 217
            }
            let mut result = ~[];
            ptr::array_each(environ, |e| {
                let env_pair = str::raw::from_c_str(e);
B
Brian Anderson 已提交
218 219
                debug!("get_env_pairs: %s",
                       env_pair);
220 221 222 223 224 225
                result.push(env_pair);
            });
            result
        }

        fn env_convert(input: ~[~str]) -> ~[(~str, ~str)] {
226
            let mut pairs = ~[];
227
            for input.iter().advance |p| {
228
                let vs: ~[&str] = p.splitn_iter('=', 1).collect();
B
Brian Anderson 已提交
229 230
                debug!("splitting: len: %u",
                    vs.len());
231
                assert_eq!(vs.len(), 2);
232
                pairs.push((vs[0].to_owned(), vs[1].to_owned()));
233
            }
L
Luqman Aden 已提交
234
            pairs
235
        }
236 237 238 239
        do with_env_lock {
            let unparsed_environ = get_env_pairs();
            env_convert(unparsed_environ)
        }
240
    }
241
}
242

243
#[cfg(unix)]
244 245
/// Fetches the environment variable `n` from the current process, returning
/// None if the variable isn't set.
246 247 248 249
pub fn getenv(n: &str) -> Option<~str> {
    unsafe {
        do with_env_lock {
            let s = str::as_c_str(n, |s| libc::getenv(s));
250
            if ptr::null::<u8>() == cast::transmute(s) {
251
                None::<~str>
252
            } else {
253
                let s = cast::transmute(s);
254
                Some::<~str>(str::raw::from_buf(s))
255
            }
256
        }
257 258
    }
}
259

260
#[cfg(windows)]
261 262
/// Fetches the environment variable `n` from the current process, returning
/// None if the variable isn't set.
263 264 265 266 267 268 269
pub fn getenv(n: &str) -> Option<~str> {
    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)
270 271 272
                }
            }
        }
273 274
    }
}
275 276


277
#[cfg(unix)]
278 279
/// Sets the environment variable `n` to the value `v` for the currently running
/// process
280 281 282 283 284 285
pub fn setenv(n: &str, v: &str) {
    unsafe {
        do with_env_lock {
            do str::as_c_str(n) |nbuf| {
                do str::as_c_str(v) |vbuf| {
                    libc::funcs::posix01::unistd::setenv(nbuf, vbuf, 1);
286 287 288
                }
            }
        }
289 290
    }
}
291 292


293
#[cfg(windows)]
294 295
/// Sets the environment variable `n` to the value `v` for the currently running
/// process
296 297 298 299 300 301 302
pub fn setenv(n: &str, v: &str) {
    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);
303 304 305 306 307 308
                }
            }
        }
    }
}

C
Corey Richardson 已提交
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
/// Remove a variable from the environment entirely
pub fn unsetenv(n: &str) {
    #[cfg(unix)]
    fn _unsetenv(n: &str) {
        unsafe {
            do with_env_lock {
                do str::as_c_str(n) |nbuf| {
                    libc::funcs::posix01::unistd::unsetenv(nbuf);
                }
            }
        }
    }
    #[cfg(windows)]
    fn _unsetenv(n: &str) {
        unsafe {
            do with_env_lock {
                use os::win32::as_utf16_p;
                do as_utf16_p(n) |nbuf| {
                    libc::SetEnvironmentVariableW(nbuf, ptr::null());
                }
            }
        }
    }

    _unsetenv(n);
}

336
pub fn fdopen(fd: c_int) -> *FILE {
337 338 339 340 341
    unsafe {
        return do as_c_charp("r") |modebuf| {
            libc::fdopen(fd, modebuf)
        };
    }
342 343 344
}


345 346
// fsync related

347
#[cfg(windows)]
348
pub fn fsync_fd(fd: c_int, _level: io::fsync::Level) -> c_int {
349 350 351 352
    unsafe {
        use libc::funcs::extra::msvcrt::*;
        return commit(fd);
    }
353 354 355
}

#[cfg(target_os = "linux")]
K
kyeongwoon 已提交
356
#[cfg(target_os = "android")]
357
pub fn fsync_fd(fd: c_int, level: io::fsync::Level) -> c_int {
358 359 360 361 362 363 364
    unsafe {
        use libc::funcs::posix01::unistd::*;
        match level {
          io::fsync::FSync
          | io::fsync::FullFSync => return fsync(fd),
          io::fsync::FDataSync => return fdatasync(fd)
        }
365 366 367 368
    }
}

#[cfg(target_os = "macos")]
369
pub fn fsync_fd(fd: c_int, level: io::fsync::Level) -> c_int {
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
    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; }
          }
        }
385 386 387 388
    }
}

#[cfg(target_os = "freebsd")]
389
pub fn fsync_fd(fd: c_int, _l: io::fsync::Level) -> c_int {
390 391 392 393
    unsafe {
        use libc::funcs::posix01::unistd::*;
        return fsync(fd);
    }
394 395
}

396 397 398 399
pub struct Pipe {
    in: c_int,
    out: c_int
}
400

401
#[cfg(unix)]
402
pub fn pipe() -> Pipe {
403
    unsafe {
404
        let mut fds = Pipe {in: 0 as c_int,
405
                            out: 0 as c_int };
406
        assert_eq!(libc::pipe(&mut fds.in), (0 as c_int));
407
        return Pipe {in: fds.in, out: fds.out};
408
    }
409 410 411 412
}



413
#[cfg(windows)]
414
pub fn pipe() -> Pipe {
415 416 417 418 419
    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
420
        // first, as in core::run.
421 422
        let mut fds = Pipe {in: 0 as c_int,
                    out: 0 as c_int };
A
Alex Crichton 已提交
423
        let res = libc::pipe(&mut fds.in, 1024 as ::libc::c_uint,
424
                             (libc::O_BINARY | libc::O_NOINHERIT) as c_int);
425
        assert_eq!(res, 0 as c_int);
P
Patrick Walton 已提交
426 427
        assert!((fds.in != -1 as c_int && fds.in != 0 as c_int));
        assert!((fds.out != -1 as c_int && fds.in != 0 as c_int));
428
        return Pipe {in: fds.in, out: fds.out};
429
    }
430 431
}

P
Patrick Walton 已提交
432
fn dup2(src: c_int, dst: c_int) -> c_int {
433 434 435
    unsafe {
        libc::dup2(src, dst)
    }
P
Patrick Walton 已提交
436 437
}

438
/// Returns the proper dll filename for the given basename of a file.
439
pub fn dll_filename(base: &str) -> ~str {
440
    fmt!("%s%s%s", DLL_PREFIX, base, DLL_SUFFIX)
441 442
}

443 444
/// Optionally returns the filesystem path to the current executable which is
/// running. If any failure occurs, None is returned.
445
pub fn self_exe_path() -> Option<Path> {
446 447

    #[cfg(target_os = "freebsd")]
B
Brian Anderson 已提交
448
    fn load_self() -> Option<~str> {
449
        unsafe {
450 451
            use libc::funcs::bsd44::*;
            use libc::consts::os::extra::*;
B
Brian Anderson 已提交
452
            do fill_charp_buf() |buf, sz| {
453
                let mib = ~[CTL_KERN as c_int,
454
                           KERN_PROC as c_int,
455
                           KERN_PROC_PATHNAME as c_int, -1 as c_int];
T
Tim Chevalier 已提交
456
                let mut sz = sz;
Y
Youngmin Yoo 已提交
457
                sysctl(vec::raw::to_ptr(mib), mib.len() as ::libc::c_uint,
G
Graydon Hoare 已提交
458
                       buf as *mut c_void, &mut sz, ptr::null(),
459
                       0u as size_t) == (0 as c_int)
460
            }
461
        }
462 463 464
    }

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

470
            let mut path_str = str::with_capacity(TMPBUF_SZ);
471 472
            let len = do str::as_c_str(path_str) |buf| {
                let buf = buf as *mut c_char;
473
                do as_c_charp("/proc/self/exe") |proc_self_buf| {
474
                    readlink(proc_self_buf, buf, TMPBUF_SZ as size_t)
475
                }
476 477 478 479 480 481
            };
            if len == -1 {
                None
            } else {
                str::raw::set_len(&mut path_str, len as uint);
                Some(path_str)
482
            }
483 484 485
        }
    }

486
    #[cfg(target_os = "macos")]
B
Brian Anderson 已提交
487
    fn load_self() -> Option<~str> {
488 489
        unsafe {
            do fill_charp_buf() |buf, sz| {
490
                let mut sz = sz as u32;
491
                libc::funcs::extra::_NSGetExecutablePath(
492
                    buf, &mut sz) == (0 as c_int)
493
            }
494
        }
495 496
    }

497
    #[cfg(windows)]
B
Brian Anderson 已提交
498
    fn load_self() -> Option<~str> {
499 500 501 502 503
        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)
            }
504
        }
505 506
    }

B
Brian Anderson 已提交
507
    do load_self().map |pth| {
508
        Path(*pth).dir_path()
509
    }
510 511 512
}


513 514 515 516 517 518 519 520 521 522 523 524 525
/**
 * 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.
 */
526
pub fn homedir() -> Option<Path> {
527
    return match getenv("HOME") {
528
        Some(ref p) => if !p.is_empty() {
B
Brian Anderson 已提交
529
          Some(Path(*p))
B
Brian Anderson 已提交
530 531
        } else {
          secondary()
532
        },
B
Brian Anderson 已提交
533
        None => secondary()
534 535
    };

536
    #[cfg(unix)]
B
Brian Anderson 已提交
537 538
    fn secondary() -> Option<Path> {
        None
539 540
    }

541
    #[cfg(windows)]
B
Brian Anderson 已提交
542
    fn secondary() -> Option<Path> {
543
        do getenv("USERPROFILE").chain |p| {
544
            if !p.is_empty() {
B
Brian Anderson 已提交
545
                Some(Path(p))
546
            } else {
B
Brian Anderson 已提交
547
                None
548 549 550 551 552
            }
        }
    }
}

553
/**
554
 * Returns the path to a temporary directory.
555 556 557 558 559
 *
 * On Unix, returns the value of the 'TMPDIR' environment variable if it is
 * set and non-empty and '/tmp' otherwise.
 *
 * On Windows, returns the value of, in order, the 'TMP', 'TEMP',
560 561
 * 'USERPROFILE' environment variable  if any are set and not the empty
 * string. Otherwise, tmpdir returns the path to the Windows directory.
562
 */
563
pub fn tmpdir() -> Path {
564 565
    return lookup();

B
Brian Anderson 已提交
566
    fn getenv_nonempty(v: &str) -> Option<Path> {
567
        match getenv(v) {
L
Luqman Aden 已提交
568
            Some(x) =>
569
                if x.is_empty() {
B
Brian Anderson 已提交
570
                    None
571
                } else {
B
Brian Anderson 已提交
572
                    Some(Path(x))
573
                },
B
Brian Anderson 已提交
574
            _ => None
575 576 577 578
        }
    }

    #[cfg(unix)]
579
    #[allow(non_implicitly_copyable_typarams)]
580
    fn lookup() -> Path {
581
        getenv_nonempty("TMPDIR").get_or_default(Path("/tmp"))
582 583 584
    }

    #[cfg(windows)]
585
    #[allow(non_implicitly_copyable_typarams)]
586
    fn lookup() -> Path {
587 588 589 590
        getenv_nonempty("TMP").or(
            getenv_nonempty("TEMP").or(
                getenv_nonempty("USERPROFILE").or(
                   getenv_nonempty("WINDIR")))).get_or_default(Path("C:\\Windows"))
591 592
    }
}
B
Brian Anderson 已提交
593

594
/// Recursively walk a directory structure
A
Alex Crichton 已提交
595
pub fn walk_dir(p: &Path, f: &fn(&Path) -> bool) -> bool {
596 597
    let r = list_dir(p);
    r.iter().advance(|q| {
A
Alex Crichton 已提交
598
        let path = &p.push(*q);
599
        f(path) && (!path_is_dir(path) || walk_dir(path, |p| f(p)))
A
Alex Crichton 已提交
600 601
    })
}
602

603
/// Indicates whether a path represents a directory
604
pub fn path_is_dir(p: &Path) -> bool {
605 606 607 608
    unsafe {
        do str::as_c_str(p.to_str()) |buf| {
            rustrt::rust_path_is_dir(buf) != 0 as c_int
        }
609
    }
610 611
}

612
/// Indicates whether a path exists
613
pub fn path_exists(p: &Path) -> bool {
614 615 616 617
    unsafe {
        do str::as_c_str(p.to_str()) |buf| {
            rustrt::rust_path_exists(buf) != 0 as c_int
        }
618
    }
619 620
}

621 622 623 624 625
/**
 * 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
626
 * as is.
627
 */
628 629 630
// 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.
631
pub fn make_absolute(p: &Path) -> Path {
632 633 634 635 636
    if p.is_absolute {
        copy *p
    } else {
        getcwd().push_many(p.components)
    }
637 638 639
}


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

644
    #[cfg(windows)]
645
    fn mkdir(p: &Path, _mode: c_int) -> bool {
646 647 648 649
        unsafe {
            use os::win32::as_utf16_p;
            // FIXME: turn mode into something useful? #2623
            do as_utf16_p(p.to_str()) |buf| {
650
                libc::CreateDirectoryW(buf, cast::transmute(0))
651 652
                    != (0 as libc::BOOL)
            }
653
        }
654 655
    }

656
    #[cfg(unix)]
657
    fn mkdir(p: &Path, mode: c_int) -> bool {
658 659
        unsafe {
            do as_c_charp(p.to_str()) |c| {
660
                libc::mkdir(c, mode as libc::mode_t) == (0 as c_int)
661
            }
662
        }
663 664 665
    }
}

666 667 668 669
/// 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.
670 671 672

// tjc: if directory exists but with different permissions,
// should we return false?
673 674 675 676
pub fn mkdir_recursive(p: &Path, mode: c_int) -> bool {
    if path_is_dir(p) {
        return true;
    }
677 678 679 680
    else if p.components.is_empty() {
        return false;
    }
    else if p.components.len() == 1 {
681
        // No parent directories to create
682
        path_is_dir(p) || make_dir(p, mode)
683 684
    }
    else {
685
        mkdir_recursive(&p.pop(), mode) && make_dir(p, mode)
686 687 688
    }
}

689
/// Lists the contents of a directory
690
#[allow(non_implicitly_copyable_typarams)]
691
pub fn list_dir(p: &Path) -> ~[~str] {
692
    if p.components.is_empty() && !p.is_absolute() {
693 694 695 696
        // Not sure what the right behavior is here, but this
        // prevents a bounds check failure later
        return ~[];
    }
697
    unsafe {
698 699 700 701 702
        #[cfg(target_os = "linux")]
        #[cfg(target_os = "android")]
        #[cfg(target_os = "freebsd")]
        #[cfg(target_os = "macos")]
        unsafe fn get_list(p: &Path) -> ~[~str] {
A
Alex Crichton 已提交
703
            use libc::{dirent_t};
704
            use libc::{opendir, readdir, closedir};
705 706
            extern {
                unsafe fn rust_list_dir_val(ptr: *dirent_t) -> *libc::c_char;
707 708 709 710
            }
            let input = p.to_str();
            let mut strings = ~[];
            let input_ptr = ::cast::transmute(&input[0]);
B
Brian Anderson 已提交
711
            debug!("os::list_dir -- BEFORE OPENDIR");
712 713
            let dir_ptr = opendir(input_ptr);
            if (dir_ptr as uint != 0) {
B
Brian Anderson 已提交
714
        debug!("os::list_dir -- opendir() SUCCESS");
715 716
                let mut entry_ptr = readdir(dir_ptr);
                while (entry_ptr as uint != 0) {
717 718
                    strings.push(str::raw::from_c_str(rust_list_dir_val(
                        entry_ptr)));
719 720 721 722 723
                    entry_ptr = readdir(dir_ptr);
                }
                closedir(dir_ptr);
            }
            else {
B
Brian Anderson 已提交
724
        debug!("os::list_dir -- opendir() FAILURE");
725
            }
B
Brian Anderson 已提交
726 727 728
            debug!(
                "os::list_dir -- AFTER -- #: %?",
                     strings.len());
729 730
            strings
        }
731
        #[cfg(windows)]
732 733
        unsafe fn get_list(p: &Path) -> ~[~str] {
            use libc::consts::os::extra::INVALID_HANDLE_VALUE;
D
Daniel Micay 已提交
734
            use libc::{wcslen, free};
735 736 737 738 739 740 741 742
            use libc::funcs::extra::kernel32::{
                FindFirstFileW,
                FindNextFileW,
                FindClose,
            };
            use os::win32::{
                as_utf16_p
            };
D
Daniel Micay 已提交
743
            use rt::global_heap::malloc_raw;
744

745
            #[nolink]
746
            extern {
747 748 749 750 751 752 753
                unsafe fn rust_list_dir_wfd_size() -> libc::size_t;
                unsafe fn rust_list_dir_wfd_fp_buf(wfd: *libc::c_void)
                    -> *u16;
            }
            fn star(p: &Path) -> Path { p.push("*") }
            do as_utf16_p(star(p).to_str()) |path_ptr| {
                let mut strings = ~[];
754
                let wfd_ptr = malloc_raw(rust_list_dir_wfd_size() as uint);
755 756 757 758
                let find_handle =
                    FindFirstFileW(
                        path_ptr,
                        ::cast::transmute(wfd_ptr));
759
                if find_handle as libc::c_int != INVALID_HANDLE_VALUE {
760 761
                    let mut more_files = 1 as libc::c_int;
                    while more_files != 0 {
762
                        let fp_buf = rust_list_dir_wfd_fp_buf(wfd_ptr);
763
                        if fp_buf as uint == 0 {
764
                            fail!("os::list_dir() failure: got null ptr from wfd");
765 766 767 768 769 770 771 772 773 774 775 776
                        }
                        else {
                            let fp_vec = vec::from_buf(
                                fp_buf, wcslen(fp_buf) as uint);
                            let fp_str = str::from_utf16(fp_vec);
                            strings.push(fp_str);
                        }
                        more_files = FindNextFileW(
                            find_handle,
                            ::cast::transmute(wfd_ptr));
                    }
                    FindClose(find_handle);
D
Daniel Micay 已提交
777
                    free(wfd_ptr)
778 779 780 781
                }
                strings
            }
        }
782 783 784
        do get_list(p).consume_iter().filter |filename| {
            "." != *filename && ".." != *filename
        }.collect()
785 786 787
    }
}

788 789 790 791 792
/**
 * Lists the contents of a directory
 *
 * This version prepends each entry with the directory.
 */
793
pub fn list_dir_path(p: &Path) -> ~[~Path] {
E
Erick Tryzelaar 已提交
794
    list_dir(p).map(|f| ~p.push(*f))
795 796
}

797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818
/// 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;
    for walk_dir(p) |inner| {
        if !error_happened {
            if path_is_dir(inner) {
                if !remove_dir_recursive(inner) {
                    error_happened = true;
                }
            }
            else {
                if !remove_file(inner) {
                    error_happened = true;
                }
            }
        }
    };
    // Directory should now be empty
    !error_happened && remove_dir(p)
}

819
/// Removes a directory at the specified path
820
pub fn remove_dir(p: &Path) -> bool {
B
Brian Anderson 已提交
821
   return rmdir(p);
822

823
    #[cfg(windows)]
824
    fn rmdir(p: &Path) -> bool {
825 826 827 828 829 830
        unsafe {
            use os::win32::as_utf16_p;
            return do as_utf16_p(p.to_str()) |buf| {
                libc::RemoveDirectoryW(buf) != (0 as libc::BOOL)
            };
        }
831 832
    }

833
    #[cfg(unix)]
834
    fn rmdir(p: &Path) -> bool {
835 836 837 838 839
        unsafe {
            return do as_c_charp(p.to_str()) |buf| {
                libc::rmdir(buf) == (0 as c_int)
            };
        }
840 841 842
    }
}

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

848
    #[cfg(windows)]
849
    fn chdir(p: &Path) -> bool {
850 851 852 853 854 855
        unsafe {
            use os::win32::as_utf16_p;
            return do as_utf16_p(p.to_str()) |buf| {
                libc::SetCurrentDirectoryW(buf) != (0 as libc::BOOL)
            };
        }
856 857
    }

858
    #[cfg(unix)]
859
    fn chdir(p: &Path) -> bool {
860 861 862 863 864
        unsafe {
            return do as_c_charp(p.to_str()) |buf| {
                libc::chdir(buf) == (0 as c_int)
            };
        }
865 866 867
    }
}

868 869 870 871 872 873 874 875
/// Changes the current working directory to the specified
/// path while acquiring a global lock, then calls `action`.
/// If the change is successful, releases the lock and restores the
/// CWD to what it was before, returning true.
/// Returns false if the directory doesn't exist or if the directory change
/// is otherwise unsuccessful.
pub fn change_dir_locked(p: &Path, action: &fn()) -> bool {
    use unstable::global::global_data_clone_create;
876
    use unstable::sync::{Exclusive, exclusive};
877 878 879

    fn key(_: Exclusive<()>) { }

880 881
    unsafe {
        let result = global_data_clone_create(key, || { ~exclusive(()) });
882

883 884 885 886 887 888 889 890 891
        do result.with_imm() |_| {
            let old_dir = os::getcwd();
            if change_dir(p) {
                action();
                change_dir(&old_dir)
            }
            else {
                false
            }
892 893 894 895
        }
    }
}

896
/// Copies a file from one location to another
897
pub fn copy_file(from: &Path, to: &Path) -> bool {
B
Brian Anderson 已提交
898
    return do_copy_file(from, to);
899

900
    #[cfg(windows)]
901
    fn do_copy_file(from: &Path, to: &Path) -> bool {
902 903 904 905 906 907 908
        unsafe {
            use os::win32::as_utf16_p;
            return do as_utf16_p(from.to_str()) |fromp| {
                do as_utf16_p(to.to_str()) |top| {
                    libc::CopyFileW(fromp, top, (0 as libc::BOOL)) !=
                        (0 as libc::BOOL)
                }
909 910 911 912
            }
        }
    }

913
    #[cfg(unix)]
914
    fn do_copy_file(from: &Path, to: &Path) -> bool {
915 916 917 918 919 920 921 922
        unsafe {
            let istream = do as_c_charp(from.to_str()) |fromp| {
                do as_c_charp("rb") |modebuf| {
                    libc::fopen(fromp, modebuf)
                }
            };
            if istream as uint == 0u {
                return false;
923
            }
924 925 926 927
            // Preserve permissions
            let from_mode = from.get_mode().expect("copy_file: couldn't get permissions \
                                                    for source file");

928 929 930 931 932 933 934 935
            let ostream = do as_c_charp(to.to_str()) |top| {
                do as_c_charp("w+b") |modebuf| {
                    libc::fopen(top, modebuf)
                }
            };
            if ostream as uint == 0u {
                fclose(istream);
                return false;
936
            }
937 938 939 940 941
            let bufsize = 8192u;
            let mut buf = vec::with_capacity::<u8>(bufsize);
            let mut done = false;
            let mut ok = true;
            while !done {
942
                do buf.as_mut_buf |b, _sz| {
943 944 945 946 947 948 949 950 951 952
                  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 {
953 954
                      done = true;
                  }
955
              }
956 957 958
            }
            fclose(istream);
            fclose(ostream);
959 960

            // Give the new file the old file's permissions
J
James Miller 已提交
961
            if do str::as_c_str(to.to_str()) |to_buf| {
962
                libc::chmod(to_buf, from_mode as libc::mode_t)
J
James Miller 已提交
963 964
            } != 0 {
                return false; // should be a condition...
965
            }
966
            return ok;
967 968 969 970
        }
    }
}

971
/// Deletes an existing file
972
pub fn remove_file(p: &Path) -> bool {
B
Brian Anderson 已提交
973
    return unlink(p);
974

975
    #[cfg(windows)]
976
    fn unlink(p: &Path) -> bool {
977 978 979 980 981 982
        unsafe {
            use os::win32::as_utf16_p;
            return do as_utf16_p(p.to_str()) |buf| {
                libc::DeleteFileW(buf) != (0 as libc::BOOL)
            };
        }
983 984
    }

985
    #[cfg(unix)]
986
    fn unlink(p: &Path) -> bool {
987 988 989 990 991
        unsafe {
            return do as_c_charp(p.to_str()) |buf| {
                libc::unlink(buf) == (0 as c_int)
            };
        }
992 993 994
    }
}

995
#[cfg(unix)]
996
/// Returns the platform-specific value of errno
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
pub fn errno() -> int {
    #[cfg(target_os = "macos")]
    #[cfg(target_os = "freebsd")]
    fn errno_location() -> *c_int {
        #[nolink]
        extern {
            unsafe fn __error() -> *c_int;
        }
        unsafe {
            __error()
        }
    }

    #[cfg(target_os = "linux")]
    #[cfg(target_os = "android")]
    fn errno_location() -> *c_int {
        #[nolink]
        extern {
            unsafe fn __errno_location() -> *c_int;
        }
        unsafe {
            __errno_location()
        }
    }

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

#[cfg(windows)]
1028
/// Returns the platform-specific value of errno
1029 1030 1031 1032 1033
pub fn errno() -> uint {
    use libc::types::os::arch::extra::DWORD;

    #[link_name = "kernel32"]
    #[abi = "stdcall"]
1034
    extern "stdcall" {
1035 1036 1037 1038
        unsafe fn GetLastError() -> DWORD;
    }

    unsafe {
1039
        GetLastError() as uint
1040 1041 1042
    }
}

1043
/// Get a string representing the platform-dependent last error
1044
pub fn last_os_error() -> ~str {
1045 1046 1047 1048 1049
    #[cfg(unix)]
    fn strerror() -> ~str {
        #[cfg(target_os = "macos")]
        #[cfg(target_os = "android")]
        #[cfg(target_os = "freebsd")]
1050
        fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: size_t) -> c_int {
1051 1052
            #[nolink]
            extern {
1053
                unsafe fn strerror_r(errnum: c_int, buf: *mut c_char,
1054 1055 1056 1057 1058 1059 1060 1061 1062
                                     buflen: size_t) -> c_int;
            }
            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 已提交
1063
        // So we just use __xpg_strerror_r which is always POSIX compliant
1064
        #[cfg(target_os = "linux")]
1065
        fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: size_t) -> c_int {
1066 1067
            #[nolink]
            extern {
1068
                unsafe fn __xpg_strerror_r(errnum: c_int, buf: *mut c_char,
1069 1070 1071 1072 1073 1074 1075 1076 1077
                                           buflen: size_t) -> c_int;
            }
            unsafe {
                __xpg_strerror_r(errnum, buf, buflen)
            }
        }

        let mut buf = [0 as c_char, ..TMPBUF_SZ];
        unsafe {
1078
            let err = strerror_r(errno() as c_int, &mut buf[0],
1079 1080
                                 TMPBUF_SZ as size_t);
            if err < 0 {
1081
                fail!("strerror_r failure");
1082
            }
1083

1084 1085
            str::raw::from_c_str(&buf[0])
        }
1086
    }
1087 1088 1089

    #[cfg(windows)]
    fn strerror() -> ~str {
1090 1091 1092 1093 1094 1095
        use libc::types::os::arch::extra::DWORD;
        use libc::types::os::arch::extra::LPSTR;
        use libc::types::os::arch::extra::LPVOID;

        #[link_name = "kernel32"]
        #[abi = "stdcall"]
1096
        extern "stdcall" {
1097 1098 1099 1100 1101 1102
            unsafe fn FormatMessageA(flags: DWORD, lpSrc: LPVOID,
                                     msgId: DWORD, langId: DWORD,
                                     buf: LPSTR, nsize: DWORD,
                                     args: *c_void) -> DWORD;
        }

1103 1104
        static FORMAT_MESSAGE_FROM_SYSTEM: DWORD = 0x00001000;
        static FORMAT_MESSAGE_IGNORE_INSERTS: DWORD = 0x00000200;
1105 1106 1107 1108 1109 1110 1111

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

        // This value is calculated from the macro
        // MAKELANGID(LANG_SYSTEM_DEFAULT, SUBLANG_SYS_DEFAULT)
        let langId = 0x0800 as DWORD;
        let err = errno() as DWORD;
1112
        unsafe {
1113 1114 1115
            let res = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM |
                                     FORMAT_MESSAGE_IGNORE_INSERTS,
                                     ptr::mut_null(), err, langId,
L
Luqman Aden 已提交
1116 1117
                                     &mut buf[0], TMPBUF_SZ as DWORD,
                                     ptr::null());
1118
            if res == 0 {
1119
                fail!("[%?] FormatMessage failure", errno());
1120 1121 1122
            }

            str::raw::from_c_str(&buf[0])
1123 1124 1125 1126
        }
    }

    strerror()
1127
}
1128

1129 1130 1131 1132 1133 1134 1135 1136
/**
 * 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
 */
1137
pub fn set_exit_status(code: int) {
1138 1139 1140 1141 1142 1143 1144 1145 1146
    use rt;
    use rt::OldTaskContext;

    if rt::context() == OldTaskContext {
        unsafe {
            rustrt::rust_set_exit_status(code as libc::intptr_t);
        }
    } else {
        rt::util::set_exit_status(code);
1147
    }
1148
}
1149

1150 1151 1152
unsafe fn load_argc_and_argv(argc: c_int, argv: **c_char) -> ~[~str] {
    let mut args = ~[];
    for uint::range(0, argc as uint) |i| {
1153
        args.push(str::raw::from_c_str(*argv.offset(i)));
1154
    }
L
Luqman Aden 已提交
1155
    args
1156 1157
}

1158 1159 1160 1161 1162 1163
/**
 * Returns the command line arguments
 *
 * Returns a list of the command line arguments.
 */
#[cfg(target_os = "macos")]
1164
pub fn real_args() -> ~[~str] {
1165
    unsafe {
1166 1167 1168
        let (argc, argv) = (*_NSGetArgc() as c_int,
                            *_NSGetArgv() as **c_char);
        load_argc_and_argv(argc, argv)
1169 1170 1171
    }
}

1172
#[cfg(target_os = "linux")]
K
kyeongwoon 已提交
1173
#[cfg(target_os = "android")]
1174
#[cfg(target_os = "freebsd")]
1175
pub fn real_args() -> ~[~str] {
1176 1177 1178
    use rt;
    use rt::TaskContext;

B
Brian Anderson 已提交
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
    if rt::context() == TaskContext {
        match rt::args::clone() {
            Some(args) => args,
            None => fail!("process arguments not initialized")
        }
    } else {
        unsafe {
            let argc = rustrt::rust_get_argc();
            let argv = rustrt::rust_get_argv();
            load_argc_and_argv(argc, argv)
        }
1190
    }
1191 1192
}

1193
#[cfg(windows)]
1194
pub fn real_args() -> ~[~str] {
1195
    let mut nArgs: c_int = 0;
D
Daniel Micay 已提交
1196
    let lpArgCount: *mut c_int = &mut nArgs;
T
Tim Chevalier 已提交
1197 1198
    let lpCmdLine = unsafe { GetCommandLineW() };
    let szArgList = unsafe { CommandLineToArgvW(lpCmdLine, lpArgCount) };
1199 1200 1201 1202 1203 1204 1205 1206 1207 1208

    let mut args = ~[];
    for uint::range(0, nArgs as uint) |i| {
        unsafe {
            // Determine the length of this argument.
            let ptr = *szArgList.offset(i);
            let mut len = 0;
            while *ptr.offset(len) != 0 { len += 1; }

            // Push it onto the list.
1209
            args.push(vec::raw::buf_as_slice(ptr, len,
1210
                                             str::from_utf16));
1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
        }
    }

    unsafe {
        LocalFree(cast::transmute(szArgList));
    }

    return args;
}

type LPCWSTR = *u16;

#[cfg(windows)]
#[link_name="kernel32"]
#[abi="stdcall"]
1226
extern "stdcall" {
1227 1228 1229 1230 1231 1232 1233
    fn GetCommandLineW() -> LPCWSTR;
    fn LocalFree(ptr: *c_void);
}

#[cfg(windows)]
#[link_name="shell32"]
#[abi="stdcall"]
1234
extern "stdcall" {
1235
    fn CommandLineToArgvW(lpCmdLine: LPCWSTR, pNumArgs: *mut c_int) -> **u16;
1236 1237 1238 1239 1240 1241
}

struct OverriddenArgs {
    val: ~[~str]
}

1242
#[cfg(stage0)]
T
Tim Chevalier 已提交
1243
fn overridden_arg_key(_v: @OverriddenArgs) {}
1244 1245
#[cfg(not(stage0))]
static overridden_arg_key: local_data::Key<@OverriddenArgs> = &[];
1246

1247 1248 1249 1250 1251
/// Returns the arguments which this program was started with (normally passed
/// via the command line).
///
/// The return value of the function can be changed by invoking the
/// `os::set_args` function.
1252
pub fn args() -> ~[~str] {
1253 1254 1255
    match local_data::get(overridden_arg_key, |k| k.map(|&k| *k)) {
        None => real_args(),
        Some(args) => copy args.val
1256 1257 1258
    }
}

1259 1260 1261
/// For the current task, overrides the task-local cache of the arguments this
/// program had when it started. These new arguments are only available to the
/// current task via the `os::args` method.
T
Tim Chevalier 已提交
1262
pub fn set_args(new_args: ~[~str]) {
1263 1264
    let overridden_args = @OverriddenArgs { val: copy new_args };
    local_data::set(overridden_arg_key, overridden_args);
1265 1266
}

1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344
// FIXME #6100 we should really use an internal implementation of this - using
// the POSIX glob functions isn't portable to windows, probably has slight
// inconsistencies even where it is implemented, and makes extending
// functionality a lot more difficult
// FIXME #6101 also provide a non-allocating version - each_glob or so?
/// Returns a vector of Path objects that match the given glob pattern
#[cfg(target_os = "linux")]
#[cfg(target_os = "android")]
#[cfg(target_os = "freebsd")]
#[cfg(target_os = "macos")]
pub fn glob(pattern: &str) -> ~[Path] {
    #[cfg(target_os = "linux")]
    #[cfg(target_os = "android")]
    fn default_glob_t () -> libc::glob_t {
        libc::glob_t {
            gl_pathc: 0,
            gl_pathv: ptr::null(),
            gl_offs: 0,
            __unused1: ptr::null(),
            __unused2: ptr::null(),
            __unused3: ptr::null(),
            __unused4: ptr::null(),
            __unused5: ptr::null(),
        }
    }

    #[cfg(target_os = "freebsd")]
    fn default_glob_t () -> libc::glob_t {
        libc::glob_t {
            gl_pathc: 0,
            __unused1: 0,
            gl_offs: 0,
            __unused2: 0,
            gl_pathv: ptr::null(),
            __unused3: ptr::null(),
            __unused4: ptr::null(),
            __unused5: ptr::null(),
            __unused6: ptr::null(),
            __unused7: ptr::null(),
            __unused8: ptr::null(),
        }
    }

    #[cfg(target_os = "macos")]
    fn default_glob_t () -> libc::glob_t {
        libc::glob_t {
            gl_pathc: 0,
            __unused1: 0,
            gl_offs: 0,
            __unused2: 0,
            gl_pathv: ptr::null(),
            __unused3: ptr::null(),
            __unused4: ptr::null(),
            __unused5: ptr::null(),
            __unused6: ptr::null(),
            __unused7: ptr::null(),
            __unused8: ptr::null(),
        }
    }

    let mut g = default_glob_t();
    do str::as_c_str(pattern) |c_pattern| {
        unsafe { libc::glob(c_pattern, 0, ptr::null(), &mut g) }
    };
    do(|| {
        let paths = unsafe {
            vec::raw::from_buf_raw(g.gl_pathv, g.gl_pathc as uint)
        };
        do paths.map |&c_str| {
            Path(unsafe { str::raw::from_c_str(c_str) })
        }
    }).finally {
        unsafe { libc::globfree(&mut g) };
    }
}

/// Returns a vector of Path objects that match the given glob pattern
#[cfg(target_os = "win32")]
1345
pub fn glob(_pattern: &str) -> ~[Path] {
1346
    fail!("glob() is unimplemented on Windows")
1347 1348
}

1349 1350 1351 1352 1353 1354 1355
#[cfg(target_os = "macos")]
extern {
    // These functions are in crt_externs.h.
    pub fn _NSGetArgc() -> *c_int;
    pub fn _NSGetArgv() -> ***c_char;
}

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 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 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 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637
// 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 {
    unsafe {
        libc::sysconf(libc::_SC_PAGESIZE) as uint
    }
}

#[cfg(windows)]
pub fn page_size() -> uint {
  unsafe {
    let mut info = libc::SYSTEM_INFO::new();
    libc::GetSystemInfo(&mut info);

    return info.dwPageSize as uint;
  }
}

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,
    ErrNeedRW,
    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",
            ErrUnknown(code) => fmt!("Unknown error=%?", code),
            ErrUnsupProt => ~"Protection mode unsupported",
            ErrUnsupOffset => ~"Offset in virtual memory mode is unsupported",
            ErrNeedRW => ~"File mapping should be at least readable/writable",
            ErrAlreadyExists => ~"File mapping for specified file already exists",
            ErrVirtualAlloc(code) => fmt!("VirtualAlloc failure=%?", code),
            ErrCreateFileMappingW(code) => fmt!("CreateFileMappingW failure=%?", code),
            ErrMapViewOfFile(code) => fmt!("MapViewOfFile failure=%?", code)
        }
    }
}

#[cfg(unix)]
impl MemoryMap {
    pub fn new(min_len: uint, options: ~[MapOption]) -> Result<~MemoryMap, MapError> {
        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;

        for options.iter().advance |&o| {
            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)
        };
        if r == libc::MAP_FAILED {
            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 {
            Ok(~MemoryMap {
               data: r as *mut u8,
               len: len,
               kind: if fd == -1 {
                   MapVirtual
               } else {
                   MapFile(ptr::null())
               }
            })
        }
    }
}

#[cfg(unix)]
impl Drop for MemoryMap {
    fn drop(&self) {
        unsafe {
            match libc::munmap(self.data as *c_void, self.len) {
                0 => (),
                -1 => error!(match errno() as c_int {
                    libc::EINVAL => ~"invalid addr or len",
                    e => fmt!("unknown errno=%?", e)
                }),
                r => error!(fmt!("Unexpected result %?", r))
            }
        }
    }
}

#[cfg(windows)]
impl MemoryMap {
    pub fn new(min_len: uint, options: ~[MapOption]) -> Result<~MemoryMap, MapError> {
        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;

        for options.iter().advance |&o| {
            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())),
                _ => Ok(~MemoryMap {
                   data: r as *mut u8,
                   len: len,
                   kind: MapVirtual
                })
            }
        } else {
            let dwDesiredAccess = match (readable, writable) {
                (true, true) => libc::FILE_MAP_ALL_ACCESS,
                (true, false) => libc::FILE_MAP_READ,
                (false, true) => libc::FILE_MAP_WRITE,
                _ => {
                    return Err(ErrNeedRW);
                }
            };
            unsafe {
                let hFile = libc::get_osfhandle(fd) as HANDLE;
                let mapping = libc::CreateFileMappingW(hFile,
                                                       ptr::mut_null(),
                                                       flProtect,
                                                       (len >> 32) as DWORD,
                                                       (len & 0xffff_ffff) as DWORD,
                                                       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,
                                            (offset >> 32) as DWORD,
                                            (offset & 0xffff_ffff) as DWORD,
                                            0);
                match r as uint {
                    0 => Err(ErrMapViewOfFile(errno())),
                    _ => Ok(~MemoryMap {
                       data: r as *mut u8,
                       len: len,
                       kind: MapFile(mapping as *c_void)
                    })
                }
            }
        }
    }
}

#[cfg(windows)]
impl Drop for MemoryMap {
    fn drop(&self) {
        use libc::types::os::arch::extra::{LPCVOID, HANDLE};

        unsafe {
            match self.kind {
                MapVirtual => match libc::VirtualFree(self.data as *mut c_void,
                                                      self.len,
                                                      libc::MEM_RELEASE) {
                    0 => error!(fmt!("VirtualFree failed: %?", errno())),
                    _ => ()
                },
                MapFile(mapping) => {
                    if libc::UnmapViewOfFile(self.data as LPCVOID) != 0 {
                        error!(fmt!("UnmapViewOfFile failed: %?", errno()));
                    }
                    if libc::CloseHandle(mapping as HANDLE) != 0 {
                        error!(fmt!("CloseHandle failed: %?", errno()));
                    }
                }
            }
        }
    }
}

1638
pub mod consts {
1639

I
ILyoan 已提交
1640
    #[cfg(unix)]
1641
    pub use os::consts::unix::*;
1642

I
ILyoan 已提交
1643
    #[cfg(windows)]
1644
    pub use os::consts::windows::*;
1645

I
ILyoan 已提交
1646
    #[cfg(target_os = "macos")]
1647
    pub use os::consts::macos::*;
I
ILyoan 已提交
1648 1649

    #[cfg(target_os = "freebsd")]
1650
    pub use os::consts::freebsd::*;
I
ILyoan 已提交
1651 1652

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

K
kyeongwoon 已提交
1655
    #[cfg(target_os = "android")]
1656
    pub use os::consts::android::*;
K
kyeongwoon 已提交
1657

I
ILyoan 已提交
1658
    #[cfg(target_os = "win32")]
1659
    pub use os::consts::win32::*;
1660

1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680
    #[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")]
    use os::consts::mips::*;

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

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

I
ILyoan 已提交
1681
    pub mod macos {
1682 1683 1684 1685
        pub static SYSNAME: &'static str = "macos";
        pub static DLL_PREFIX: &'static str = "lib";
        pub static DLL_SUFFIX: &'static str = ".dylib";
        pub static EXE_SUFFIX: &'static str = "";
I
ILyoan 已提交
1686 1687 1688
    }

    pub mod freebsd {
1689 1690 1691 1692
        pub static SYSNAME: &'static str = "freebsd";
        pub static DLL_PREFIX: &'static str = "lib";
        pub static DLL_SUFFIX: &'static str = ".so";
        pub static EXE_SUFFIX: &'static str = "";
I
ILyoan 已提交
1693 1694 1695
    }

    pub mod linux {
1696 1697 1698 1699
        pub static SYSNAME: &'static str = "linux";
        pub static DLL_PREFIX: &'static str = "lib";
        pub static DLL_SUFFIX: &'static str = ".so";
        pub static EXE_SUFFIX: &'static str = "";
I
ILyoan 已提交
1700
    }
K
kyeongwoon 已提交
1701 1702

    pub mod android {
1703 1704 1705 1706
        pub static SYSNAME: &'static str = "android";
        pub static DLL_PREFIX: &'static str = "lib";
        pub static DLL_SUFFIX: &'static str = ".so";
        pub static EXE_SUFFIX: &'static str = "";
K
kyeongwoon 已提交
1707
    }
1708

I
ILyoan 已提交
1709
    pub mod win32 {
1710 1711 1712 1713
        pub static SYSNAME: &'static str = "win32";
        pub static DLL_PREFIX: &'static str = "";
        pub static DLL_SUFFIX: &'static str = ".dll";
        pub static EXE_SUFFIX: &'static str = ".exe";
I
ILyoan 已提交
1714 1715 1716 1717
    }


    pub mod x86 {
1718
        pub static ARCH: &'static str = "x86";
I
ILyoan 已提交
1719 1720
    }
    pub mod x86_64 {
1721
        pub static ARCH: &'static str = "x86_64";
I
ILyoan 已提交
1722 1723
    }
    pub mod arm {
1724
        pub static ARCH: &'static str = "arm";
I
ILyoan 已提交
1725
    }
J
Jyun-Yan You 已提交
1726
    pub mod mips {
1727
        pub static ARCH: &'static str = "mips";
J
Jyun-Yan You 已提交
1728
    }
I
ILyoan 已提交
1729
}
1730 1731

#[cfg(test)]
1732
#[allow(non_implicitly_copyable_typarams)]
1733
mod tests {
1734
    use libc::{c_int, c_void, size_t};
1735
    use libc;
A
Alex Crichton 已提交
1736
    use option::Some;
1737
    use option;
1738
    use os::{as_c_charp, env, getcwd, getenv, make_absolute, real_args};
C
Corey Richardson 已提交
1739
    use os::{remove_file, setenv, unsetenv};
1740
    use os;
1741
    use path::Path;
1742
    use rand::RngUtil;
1743 1744
    use rand;
    use run;
1745
    use str::StrSlice;
1746
    use vec;
1747
    use vec::CopyableVector;
1748 1749
    use libc::consts::os::posix88::{S_IRUSR, S_IWUSR, S_IXUSR};

1750

1751
    #[test]
1752
    pub fn last_os_error() {
B
Brian Anderson 已提交
1753
        debug!(os::last_os_error());
1754
    }
1755

1756 1757 1758
    #[test]
    pub fn test_args() {
        let a = real_args();
P
Patrick Walton 已提交
1759
        assert!(a.len() >= 1);
1760 1761
    }

1762
    fn make_rand_name() -> ~str {
P
Patrick Walton 已提交
1763
        let mut rng = rand::rng();
1764
        let n = ~"TEST" + rng.gen_str(10u);
P
Patrick Walton 已提交
1765
        assert!(getenv(n).is_none());
L
Luqman Aden 已提交
1766
        n
1767 1768 1769 1770 1771
    }

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

C
Corey Richardson 已提交
1776 1777 1778
    #[test]
    fn test_unsetenv() {
        let n = make_rand_name();
E
Erick Tryzelaar 已提交
1779
        setenv(n, "VALUE");
C
Corey Richardson 已提交
1780
        unsetenv(n);
1781
        assert_eq!(getenv(n), option::None);
C
Corey Richardson 已提交
1782 1783
    }

1784
    #[test]
1785 1786
    #[ignore(cfg(windows))]
    #[ignore]
1787 1788
    fn test_setenv_overwrite() {
        let n = make_rand_name();
E
Erick Tryzelaar 已提交
1789 1790
        setenv(n, "1");
        setenv(n, "2");
1791
        assert_eq!(getenv(n), option::Some(~"2"));
E
Erick Tryzelaar 已提交
1792
        setenv(n, "");
1793
        assert_eq!(getenv(n), option::Some(~""));
1794 1795 1796 1797 1798
    }

    // Windows GetEnvironmentVariable requires some extra work to make sure
    // the buffer the variable is copied into is the right size
    #[test]
1799 1800
    #[ignore(cfg(windows))]
    #[ignore]
1801
    fn test_getenv_big() {
1802
        let mut s = ~"";
1803
        let mut i = 0;
1804 1805 1806 1807
        while i < 100 {
            s = s + "aaaaaaaaaa";
            i += 1;
        }
1808 1809
        let n = make_rand_name();
        setenv(n, s);
B
Brian Anderson 已提交
1810
        debug!(copy s);
1811
        assert_eq!(getenv(n), option::Some(s));
1812 1813 1814 1815 1816
    }

    #[test]
    fn test_self_exe_path() {
        let path = os::self_exe_path();
P
Patrick Walton 已提交
1817
        assert!(path.is_some());
B
Brian Anderson 已提交
1818
        let path = path.get();
B
Brian Anderson 已提交
1819
        debug!(copy path);
1820 1821

        // Hard to test this function
P
Patrick Walton 已提交
1822
        assert!(path.is_absolute);
1823 1824 1825
    }

    #[test]
1826
    #[ignore]
1827 1828
    fn test_env_getenv() {
        let e = env();
Y
Youngmin Yoo 已提交
1829
        assert!(e.len() > 0u);
1830
        for e.iter().advance |p| {
1831
            let (n, v) = copy *p;
B
Brian Anderson 已提交
1832
            debug!(copy n);
1833 1834 1835 1836
            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 已提交
1837
            assert!(v2.is_none() || v2 == option::Some(v));
1838 1839 1840 1841 1842 1843 1844
        }
    }

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

1845
        let mut e = env();
E
Erick Tryzelaar 已提交
1846
        setenv(n, "VALUE");
1847
        assert!(!e.contains(&(copy n, ~"VALUE")));
1848 1849

        e = env();
1850
        assert!(e.contains(&(n, ~"VALUE")));
1851 1852
    }

1853 1854
    #[test]
    fn test() {
P
Patrick Walton 已提交
1855
        assert!((!Path("test-path").is_absolute));
1856

E
Erick Tryzelaar 已提交
1857
        debug!("Current working directory: %s", getcwd().to_str());
1858

B
Brian Anderson 已提交
1859 1860
        debug!(make_absolute(&Path("test-path")));
        debug!(make_absolute(&Path("/usr/bin")));
1861 1862 1863
    }

    #[test]
1864
    #[cfg(unix)]
1865
    fn homedir() {
E
Erick Tryzelaar 已提交
1866
        let oldhome = getenv("HOME");
1867

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

E
Erick Tryzelaar 已提交
1871
        setenv("HOME", "");
P
Patrick Walton 已提交
1872
        assert!(os::homedir().is_none());
1873

1874
        for oldhome.iter().advance |s| { setenv("HOME", *s) }
1875 1876 1877
    }

    #[test]
1878
    #[cfg(windows)]
1879 1880
    fn homedir() {

E
Erick Tryzelaar 已提交
1881 1882
        let oldhome = getenv("HOME");
        let olduserprofile = getenv("USERPROFILE");
1883

E
Erick Tryzelaar 已提交
1884 1885
        setenv("HOME", "");
        setenv("USERPROFILE", "");
1886

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

E
Erick Tryzelaar 已提交
1889
        setenv("HOME", "/home/MountainView");
1890
        assert_eq!(os::homedir(), Some(Path("/home/MountainView")));
1891

E
Erick Tryzelaar 已提交
1892
        setenv("HOME", "");
1893

E
Erick Tryzelaar 已提交
1894
        setenv("USERPROFILE", "/home/MountainView");
1895
        assert_eq!(os::homedir(), Some(Path("/home/MountainView")));
1896

E
Erick Tryzelaar 已提交
1897 1898
        setenv("HOME", "/home/MountainView");
        setenv("USERPROFILE", "/home/PaloAlto");
1899
        assert_eq!(os::homedir(), Some(Path("/home/MountainView")));
1900

1901 1902
        oldhome.iter().advance(|s| { setenv("HOME", *s); true });
        olduserprofile.iter().advance(|s| { setenv("USERPROFILE", *s); true });
1903 1904
    }

1905 1906
    #[test]
    fn tmpdir() {
1907
        assert!(!os::tmpdir().to_str().is_empty());
1908 1909
    }

1910 1911
    // Issue #712
    #[test]
1912 1913 1914
    fn test_list_dir_no_invalid_memory_access() {
        os::list_dir(&Path("."));
    }
1915 1916 1917

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

1922
        for dirs.iter().advance |dir| {
B
Brian Anderson 已提交
1923
            debug!(copy *dir);
1924
        }
1925 1926
    }

1927 1928 1929 1930 1931 1932
    #[test]
    fn list_dir_empty_path() {
        let dirs = os::list_dir(&Path(""));
        assert!(dirs.is_empty());
    }

1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946
    #[test]
    #[cfg(not(windows))]
    fn list_dir_root() {
        let dirs = os::list_dir(&Path("/"));
        assert!(dirs.len() > 1);
    }
    #[test]
    #[cfg(windows)]
    fn list_dir_root() {
        let dirs = os::list_dir(&Path("C:\\"));
        assert!(dirs.len() > 1);
    }


1947 1948
    #[test]
    fn path_is_dir() {
P
Patrick Walton 已提交
1949 1950
        assert!((os::path_is_dir(&Path("."))));
        assert!((!os::path_is_dir(&Path("test/stdtest/fs.rs"))));
1951 1952 1953 1954
    }

    #[test]
    fn path_exists() {
P
Patrick Walton 已提交
1955 1956
        assert!((os::path_exists(&Path("."))));
        assert!((!os::path_exists(&Path(
P
Patrick Walton 已提交
1957
                     "test/nonexistent-bogus-path"))));
1958 1959
    }

1960 1961
    #[test]
    fn copy_file_does_not_exist() {
P
Patrick Walton 已提交
1962
      assert!(!os::copy_file(&Path("test/nonexistent-bogus-path"),
1963
                            &Path("test/other-bogus-path")));
P
Patrick Walton 已提交
1964
      assert!(!os::path_exists(&Path("test/other-bogus-path")));
1965 1966 1967 1968
    }

    #[test]
    fn copy_file_ok() {
1969 1970 1971
        unsafe {
          let tempdir = getcwd(); // would like to use $TMPDIR,
                                  // doesn't seem to work on Linux
1972
          assert!((tempdir.to_str().len() > 0u));
1973 1974 1975 1976 1977 1978 1979 1980 1981
          let in = tempdir.push("in.txt");
          let out = tempdir.push("out.txt");

          /* Write the temp input file */
            let ostream = do as_c_charp(in.to_str()) |fromp| {
                do as_c_charp("w+b") |modebuf| {
                    libc::fopen(fromp, modebuf)
                }
          };
P
Patrick Walton 已提交
1982
          assert!((ostream as uint != 0u));
1983
          let s = ~"hello";
1984
          let mut buf = s.as_bytes_with_null().to_owned();
D
Daniel Micay 已提交
1985
          let len = buf.len();
1986
          do buf.as_mut_buf |b, _len| {
D
Daniel Micay 已提交
1987 1988 1989
              assert_eq!(libc::fwrite(b as *c_void, 1u as size_t,
                                      (s.len() + 1u) as size_t, ostream),
                         len as size_t)
1990
          }
1991
          assert_eq!(libc::fclose(ostream), (0u as c_int));
1992
          let in_mode = in.get_mode();
1993 1994
          let rs = os::copy_file(&in, &out);
          if (!os::path_exists(&in)) {
1995
            fail!("%s doesn't exist", in.to_str());
1996
          }
P
Patrick Walton 已提交
1997
          assert!((rs));
1998
          let rslt = run::process_status("diff", [in.to_str(), out.to_str()]);
1999 2000
          assert_eq!(rslt, 0);
          assert_eq!(out.get_mode(), in_mode);
P
Patrick Walton 已提交
2001 2002
          assert!((remove_file(&in)));
          assert!((remove_file(&out)));
2003
        }
2004
    }
2005 2006

    #[test]
2007 2008 2009 2010
    fn recursive_mkdir_slash() {
        let path = Path("/");
        assert!(os::mkdir_recursive(&path,  (S_IRUSR | S_IWUSR | S_IXUSR) as i32));
    }
2011

2012 2013 2014 2015
    #[test]
    fn recursive_mkdir_empty() {
        let path = Path("");
        assert!(!os::mkdir_recursive(&path, (S_IRUSR | S_IWUSR | S_IXUSR) as i32));
2016 2017
    }

2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087
    #[test]
    fn memory_map_rw() {
        use result::{Ok, Err};

        let chunk = match os::MemoryMap::new(16, ~[
            os::MapReadable,
            os::MapWritable
        ]) {
            Ok(chunk) => chunk,
            Err(msg) => fail!(msg.to_str())
        };
        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::*;

        #[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);
           }
        }

        let p = tmpdir().push("mmap_file.tmp");
        let size = page_size() * 2;
        remove_file(&p);

        let fd = unsafe {
            let fd = do as_c_charp(p.to_str()) |path| {
                open(path, O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR)
            };
            lseek_(fd, size);
            do as_c_charp("x") |x| {
                assert!(write(fd, x as *c_void, 1) == 1);
            }
            fd
        };
        let chunk = match MemoryMap::new(size / 2, ~[
            MapReadable,
            MapWritable,
            MapFd(fd),
            MapOffset(size / 2)
        ]) {
            Ok(chunk) => chunk,
            Err(msg) => fail!(msg.to_str())
        };
        assert!(chunk.len > 0);

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

2088
    // More recursive_mkdir tests are in extra::tempfile
2089
}