os.rs 59.6 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::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 78 79 80 81
    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() {
                fail!()
            }

            Path(str::raw::from_c_str(buf as *c_char))
82
        }
83
    }
84 85
}

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

88 89
pub fn fill_charp_buf(f: &fn(*mut c_char, size_t) -> bool) -> Option<~str> {
    let mut buf = [0 as c_char, .. TMPBUF_SZ];
90
    do buf.as_mut_buf |b, sz| {
91 92
        if f(b, sz as size_t) {
            unsafe {
93
                Some(str::raw::from_c_str(b as *c_char))
94
            }
95
        } else {
B
Brian Anderson 已提交
96
            None
97 98 99 100
        }
    }
}

101
#[cfg(windows)]
102
pub mod win32 {
103 104 105
    use libc;
    use vec;
    use str;
106
    use option::{None, Option};
107
    use option;
108
    use os::TMPBUF_SZ;
109
    use libc::types::os::arch::extra::DWORD;
110

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

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

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

151 152 153 154 155 156 157 158 159 160 161 162
#[cfg(stage0)]
mod macro_hack {
#[macro_escape];
macro_rules! externfn(
    (fn $name:ident ()) => (
        extern {
            fn $name();
        }
    )
)
}

163 164
/*
Accessing environment variables is not generally threadsafe.
165
Serialize access through a global lock.
166 167
*/
fn with_env_lock<T>(f: &fn() -> T) -> T {
168
    use unstable::finally::Finally;
169

170
    unsafe {
171 172 173 174 175 176 177
        return do (|| {
            rust_take_env_lock();
            f()
        }).finally {
            rust_drop_env_lock();
        };
    }
178

179 180
    externfn!(fn rust_take_env_lock());
    externfn!(fn rust_drop_env_lock());
B
Ben Blum 已提交
181 182
}

183 184
/// Returns a vector of (variable, value) pairs for all the environment
/// variables of the current process.
185 186
pub fn env() -> ~[(~str,~str)] {
    unsafe {
187 188
        #[cfg(windows)]
        unsafe fn get_env_pairs() -> ~[~str] {
189 190
            #[fixed_stack_segment]; #[inline(never)];

191 192 193 194 195 196
            use libc::funcs::extra::kernel32::{
                GetEnvironmentStringsA,
                FreeEnvironmentStringsA
            };
            let ch = GetEnvironmentStringsA();
            if (ch as uint == 0) {
M
Marvin Löbel 已提交
197
                fail!("os::env() failure getting env string from OS: %s", os::last_os_error());
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
            }
            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] {
214 215
            #[fixed_stack_segment]; #[inline(never)];

216
            extern {
217
                fn rust_env_pairs() -> **libc::c_char;
218
            }
219
            let environ = rust_env_pairs();
220
            if (environ as uint == 0) {
M
Marvin Löbel 已提交
221
                fail!("os::env() failure getting env string from OS: %s", os::last_os_error());
222 223 224 225
            }
            let mut result = ~[];
            ptr::array_each(environ, |e| {
                let env_pair = str::raw::from_c_str(e);
B
Brian Anderson 已提交
226 227
                debug!("get_env_pairs: %s",
                       env_pair);
228 229 230 231 232 233
                result.push(env_pair);
            });
            result
        }

        fn env_convert(input: ~[~str]) -> ~[(~str, ~str)] {
234
            let mut pairs = ~[];
D
Daniel Micay 已提交
235
            for p in input.iter() {
236
                let vs: ~[&str] = p.splitn_iter('=', 1).collect();
B
Brian Anderson 已提交
237 238
                debug!("splitting: len: %u",
                    vs.len());
239
                assert_eq!(vs.len(), 2);
240
                pairs.push((vs[0].to_owned(), vs[1].to_owned()));
241
            }
L
Luqman Aden 已提交
242
            pairs
243
        }
244 245 246 247
        do with_env_lock {
            let unparsed_environ = get_env_pairs();
            env_convert(unparsed_environ)
        }
248
    }
249
}
250

251
#[cfg(unix)]
252 253
/// Fetches the environment variable `n` from the current process, returning
/// None if the variable isn't set.
254
pub fn getenv(n: &str) -> Option<~str> {
255
    #[fixed_stack_segment]; #[inline(never)];
256 257
    unsafe {
        do with_env_lock {
K
Kevin Ballard 已提交
258
            let s = do n.with_c_str |buf| {
259 260
                libc::getenv(buf)
            };
261
            if s.is_null() {
262
                None
263
            } else {
264
                Some(str::raw::from_c_str(s))
265
            }
266
        }
267 268
    }
}
269

270
#[cfg(windows)]
271 272
/// Fetches the environment variable `n` from the current process, returning
/// None if the variable isn't set.
273
pub fn getenv(n: &str) -> Option<~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, fill_utf16_buf_and_decode};
            do as_utf16_p(n) |u| {
                do fill_utf16_buf_and_decode() |buf, sz| {
                    libc::GetEnvironmentVariableW(u, buf, sz)
282 283 284
                }
            }
        }
285 286
    }
}
287 288


289
#[cfg(unix)]
290 291
/// Sets the environment variable `n` to the value `v` for the currently running
/// process
292
pub fn setenv(n: &str, v: &str) {
293
    #[fixed_stack_segment]; #[inline(never)];
294 295
    unsafe {
        do with_env_lock {
K
Kevin Ballard 已提交
296 297
            do n.with_c_str |nbuf| {
                do v.with_c_str |vbuf| {
298
                    libc::funcs::posix01::unistd::setenv(nbuf, vbuf, 1);
299 300 301
                }
            }
        }
302 303
    }
}
304 305


306
#[cfg(windows)]
307 308
/// Sets the environment variable `n` to the value `v` for the currently running
/// process
309
pub fn setenv(n: &str, v: &str) {
310 311
    #[fixed_stack_segment]; #[inline(never)];

312 313 314 315 316 317
    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);
318 319 320 321 322 323
                }
            }
        }
    }
}

C
Corey Richardson 已提交
324 325 326 327
/// Remove a variable from the environment entirely
pub fn unsetenv(n: &str) {
    #[cfg(unix)]
    fn _unsetenv(n: &str) {
328
        #[fixed_stack_segment]; #[inline(never)];
C
Corey Richardson 已提交
329 330
        unsafe {
            do with_env_lock {
K
Kevin Ballard 已提交
331
                do n.with_c_str |nbuf| {
C
Corey Richardson 已提交
332 333 334 335 336 337 338
                    libc::funcs::posix01::unistd::unsetenv(nbuf);
                }
            }
        }
    }
    #[cfg(windows)]
    fn _unsetenv(n: &str) {
339
        #[fixed_stack_segment]; #[inline(never)];
C
Corey Richardson 已提交
340 341 342 343 344 345 346 347 348 349 350 351 352
        unsafe {
            do with_env_lock {
                use os::win32::as_utf16_p;
                do as_utf16_p(n) |nbuf| {
                    libc::SetEnvironmentVariableW(nbuf, ptr::null());
                }
            }
        }
    }

    _unsetenv(n);
}

353
pub fn fdopen(fd: c_int) -> *FILE {
354
    #[fixed_stack_segment]; #[inline(never)];
K
Kevin Ballard 已提交
355
    do "r".with_c_str |modebuf| {
E
Erick Tryzelaar 已提交
356
        unsafe {
357
            libc::fdopen(fd, modebuf)
E
Erick Tryzelaar 已提交
358
        }
359
    }
360 361 362
}


363 364
// fsync related

365
#[cfg(windows)]
366
pub fn fsync_fd(fd: c_int, _level: io::fsync::Level) -> c_int {
367
    #[fixed_stack_segment]; #[inline(never)];
368 369 370 371
    unsafe {
        use libc::funcs::extra::msvcrt::*;
        return commit(fd);
    }
372 373 374
}

#[cfg(target_os = "linux")]
K
kyeongwoon 已提交
375
#[cfg(target_os = "android")]
376
pub fn fsync_fd(fd: c_int, level: io::fsync::Level) -> c_int {
377
    #[fixed_stack_segment]; #[inline(never)];
378 379 380 381 382 383 384
    unsafe {
        use libc::funcs::posix01::unistd::*;
        match level {
          io::fsync::FSync
          | io::fsync::FullFSync => return fsync(fd),
          io::fsync::FDataSync => return fdatasync(fd)
        }
385 386 387 388
    }
}

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

392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
    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; }
          }
        }
407 408 409 410
    }
}

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

414 415 416 417
    unsafe {
        use libc::funcs::posix01::unistd::*;
        return fsync(fd);
    }
418 419
}

420
pub struct Pipe {
421
    input: c_int,
422 423
    out: c_int
}
424

425
#[cfg(unix)]
426
pub fn pipe() -> Pipe {
427
    #[fixed_stack_segment]; #[inline(never)];
428
    unsafe {
429
        let mut fds = Pipe {input: 0 as c_int,
430
                            out: 0 as c_int };
431 432
        assert_eq!(libc::pipe(&mut fds.input), (0 as c_int));
        return Pipe {input: fds.input, out: fds.out};
433
    }
434 435 436 437
}



438
#[cfg(windows)]
439
pub fn pipe() -> Pipe {
440
    #[fixed_stack_segment]; #[inline(never)];
441 442 443 444 445
    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
446
        // first, as in std::run.
447
        let mut fds = Pipe {input: 0 as c_int,
448
                    out: 0 as c_int };
449
        let res = libc::pipe(&mut fds.input, 1024 as ::libc::c_uint,
450
                             (libc::O_BINARY | libc::O_NOINHERIT) as c_int);
451
        assert_eq!(res, 0 as c_int);
452 453 454
        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};
455
    }
456 457
}

P
Patrick Walton 已提交
458
fn dup2(src: c_int, dst: c_int) -> c_int {
459
    #[fixed_stack_segment]; #[inline(never)];
460 461 462
    unsafe {
        libc::dup2(src, dst)
    }
P
Patrick Walton 已提交
463 464
}

465
/// Returns the proper dll filename for the given basename of a file.
466
pub fn dll_filename(base: &str) -> ~str {
467
    fmt!("%s%s%s", DLL_PREFIX, base, DLL_SUFFIX)
468 469
}

470 471
/// Optionally returns the filesystem path to the current executable which is
/// running. If any failure occurs, None is returned.
472
pub fn self_exe_path() -> Option<Path> {
473 474

    #[cfg(target_os = "freebsd")]
B
Brian Anderson 已提交
475
    fn load_self() -> Option<~str> {
476
        #[fixed_stack_segment]; #[inline(never)];
477
        unsafe {
478 479
            use libc::funcs::bsd44::*;
            use libc::consts::os::extra::*;
B
Brian Anderson 已提交
480
            do fill_charp_buf() |buf, sz| {
481
                let mib = ~[CTL_KERN as c_int,
482
                           KERN_PROC as c_int,
483
                           KERN_PROC_PATHNAME as c_int, -1 as c_int];
T
Tim Chevalier 已提交
484
                let mut sz = sz;
Y
Youngmin Yoo 已提交
485
                sysctl(vec::raw::to_ptr(mib), mib.len() as ::libc::c_uint,
G
Graydon Hoare 已提交
486
                       buf as *mut c_void, &mut sz, ptr::null(),
487
                       0u as size_t) == (0 as c_int)
488
            }
489
        }
490 491 492
    }

    #[cfg(target_os = "linux")]
K
kyeongwoon 已提交
493
    #[cfg(target_os = "android")]
B
Brian Anderson 已提交
494
    fn load_self() -> Option<~str> {
495
        #[fixed_stack_segment]; #[inline(never)];
496 497
        unsafe {
            use libc::funcs::posix01::unistd::readlink;
498

499 500 501
            let mut path = [0 as c_char, .. TMPBUF_SZ];

            do path.as_mut_buf |buf, len| {
K
Kevin Ballard 已提交
502
                let len = do "/proc/self/exe".with_c_str |proc_self_buf| {
503 504 505 506 507 508 509
                    readlink(proc_self_buf, buf, len as size_t) as uint
                };

                if len == -1 {
                    None
                } else {
                    Some(str::raw::from_buf_len(buf as *u8, len))
510
                }
511
            }
512 513 514
        }
    }

515
    #[cfg(target_os = "macos")]
B
Brian Anderson 已提交
516
    fn load_self() -> Option<~str> {
517
        #[fixed_stack_segment]; #[inline(never)];
518 519
        unsafe {
            do fill_charp_buf() |buf, sz| {
520
                let mut sz = sz as u32;
521
                libc::funcs::extra::_NSGetExecutablePath(
522
                    buf, &mut sz) == (0 as c_int)
523
            }
524
        }
525 526
    }

527
    #[cfg(windows)]
B
Brian Anderson 已提交
528
    fn load_self() -> Option<~str> {
529
        #[fixed_stack_segment]; #[inline(never)];
530 531 532 533 534
        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)
            }
535
        }
536 537
    }

538
    load_self().map_move(|path| Path(path).dir_path())
539 540 541
}


542 543 544 545 546 547 548 549 550 551 552 553 554
/**
 * 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.
 */
555
pub fn homedir() -> Option<Path> {
556
    return match getenv("HOME") {
557
        Some(ref p) => if !p.is_empty() {
B
Brian Anderson 已提交
558
          Some(Path(*p))
B
Brian Anderson 已提交
559 560
        } else {
          secondary()
561
        },
B
Brian Anderson 已提交
562
        None => secondary()
563 564
    };

565
    #[cfg(unix)]
B
Brian Anderson 已提交
566 567
    fn secondary() -> Option<Path> {
        None
568 569
    }

570
    #[cfg(windows)]
B
Brian Anderson 已提交
571
    fn secondary() -> Option<Path> {
572
        do getenv("USERPROFILE").chain |p| {
573
            if !p.is_empty() {
B
Brian Anderson 已提交
574
                Some(Path(p))
575
            } else {
B
Brian Anderson 已提交
576
                None
577 578 579 580 581
            }
        }
    }
}

582
/**
583
 * Returns the path to a temporary directory.
584 585 586
 *
 * On Unix, returns the value of the 'TMPDIR' environment variable if it is
 * set and non-empty and '/tmp' otherwise.
587 588
 * On Android, there is no global temporary folder (it is usually allocated
 * per-app), hence returns '/data/tmp' which is commonly used.
589 590
 *
 * On Windows, returns the value of, in order, the 'TMP', 'TEMP',
591 592
 * 'USERPROFILE' environment variable  if any are set and not the empty
 * string. Otherwise, tmpdir returns the path to the Windows directory.
593
 */
594
pub fn tmpdir() -> Path {
595 596
    return lookup();

B
Brian Anderson 已提交
597
    fn getenv_nonempty(v: &str) -> Option<Path> {
598
        match getenv(v) {
L
Luqman Aden 已提交
599
            Some(x) =>
600
                if x.is_empty() {
B
Brian Anderson 已提交
601
                    None
602
                } else {
B
Brian Anderson 已提交
603
                    Some(Path(x))
604
                },
B
Brian Anderson 已提交
605
            _ => None
606 607 608 609
        }
    }

    #[cfg(unix)]
610
    fn lookup() -> Path {
611 612 613
        if cfg!(target_os = "android") {
            Path("/data/tmp")
        } else {
614
            getenv_nonempty("TMPDIR").unwrap_or(Path("/tmp"))
615
        }
616 617 618
    }

    #[cfg(windows)]
619
    fn lookup() -> Path {
620 621 622
        getenv_nonempty("TMP").or(
            getenv_nonempty("TEMP").or(
                getenv_nonempty("USERPROFILE").or(
623
                   getenv_nonempty("WINDIR")))).unwrap_or_default(Path("C:\\Windows"))
624 625
    }
}
B
Brian Anderson 已提交
626

627
/// Recursively walk a directory structure
A
Alex Crichton 已提交
628
pub fn walk_dir(p: &Path, f: &fn(&Path) -> bool) -> bool {
629 630
    let r = list_dir(p);
    r.iter().advance(|q| {
A
Alex Crichton 已提交
631
        let path = &p.push(*q);
632
        f(path) && (!path_is_dir(path) || walk_dir(path, |p| f(p)))
A
Alex Crichton 已提交
633 634
    })
}
635

636
/// Indicates whether a path represents a directory
637
pub fn path_is_dir(p: &Path) -> bool {
638
    #[fixed_stack_segment]; #[inline(never)];
639
    unsafe {
K
Kevin Ballard 已提交
640
        do p.with_c_str |buf| {
641 642
            rustrt::rust_path_is_dir(buf) != 0 as c_int
        }
643
    }
644 645
}

646
/// Indicates whether a path exists
647
pub fn path_exists(p: &Path) -> bool {
648
    #[fixed_stack_segment]; #[inline(never)];
649
    unsafe {
K
Kevin Ballard 已提交
650
        do p.with_c_str |buf| {
651 652
            rustrt::rust_path_exists(buf) != 0 as c_int
        }
653
    }
654 655
}

656 657 658 659 660
/**
 * 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
661
 * as is.
662
 */
663 664 665
// 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.
666
pub fn make_absolute(p: &Path) -> Path {
667
    if p.is_absolute {
668
        (*p).clone()
669 670 671
    } else {
        getcwd().push_many(p.components)
    }
672 673 674
}


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

679
    #[cfg(windows)]
680
    fn mkdir(p: &Path, _mode: c_int) -> bool {
681
        #[fixed_stack_segment]; #[inline(never)];
682 683 684 685
        unsafe {
            use os::win32::as_utf16_p;
            // FIXME: turn mode into something useful? #2623
            do as_utf16_p(p.to_str()) |buf| {
686
                libc::CreateDirectoryW(buf, ptr::mut_null())
687 688
                    != (0 as libc::BOOL)
            }
689
        }
690 691
    }

692
    #[cfg(unix)]
693
    fn mkdir(p: &Path, mode: c_int) -> bool {
694
        #[fixed_stack_segment]; #[inline(never)];
K
Kevin Ballard 已提交
695
        do p.with_c_str |buf| {
E
Erick Tryzelaar 已提交
696 697
            unsafe {
                libc::mkdir(buf, mode as libc::mode_t) == (0 as c_int)
698
            }
699
        }
700 701 702
    }
}

703 704 705 706
/// 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.
707 708 709

// tjc: if directory exists but with different permissions,
// should we return false?
710 711 712 713
pub fn mkdir_recursive(p: &Path, mode: c_int) -> bool {
    if path_is_dir(p) {
        return true;
    }
714 715 716 717
    else if p.components.is_empty() {
        return false;
    }
    else if p.components.len() == 1 {
718
        // No parent directories to create
719
        path_is_dir(p) || make_dir(p, mode)
720 721
    }
    else {
722
        mkdir_recursive(&p.pop(), mode) && make_dir(p, mode)
723 724 725
    }
}

726
/// Lists the contents of a directory
727
pub fn list_dir(p: &Path) -> ~[~str] {
728
    if p.components.is_empty() && !p.is_absolute() {
729 730 731 732
        // Not sure what the right behavior is here, but this
        // prevents a bounds check failure later
        return ~[];
    }
733
    unsafe {
734 735 736 737 738
        #[cfg(target_os = "linux")]
        #[cfg(target_os = "android")]
        #[cfg(target_os = "freebsd")]
        #[cfg(target_os = "macos")]
        unsafe fn get_list(p: &Path) -> ~[~str] {
739
            #[fixed_stack_segment]; #[inline(never)];
A
Alex Crichton 已提交
740
            use libc::{dirent_t};
741
            use libc::{opendir, readdir, closedir};
742
            extern {
743
                fn rust_list_dir_val(ptr: *dirent_t) -> *libc::c_char;
744 745
            }
            let mut strings = ~[];
B
Brian Anderson 已提交
746
            debug!("os::list_dir -- BEFORE OPENDIR");
747

K
Kevin Ballard 已提交
748
            let dir_ptr = do p.with_c_str |buf| {
749 750 751
                opendir(buf)
            };

752
            if (dir_ptr as uint != 0) {
753
                debug!("os::list_dir -- opendir() SUCCESS");
754 755
                let mut entry_ptr = readdir(dir_ptr);
                while (entry_ptr as uint != 0) {
756 757
                    strings.push(str::raw::from_c_str(rust_list_dir_val(
                        entry_ptr)));
758 759 760 761 762
                    entry_ptr = readdir(dir_ptr);
                }
                closedir(dir_ptr);
            }
            else {
763
                debug!("os::list_dir -- opendir() FAILURE");
764
            }
B
Brian Anderson 已提交
765 766 767
            debug!(
                "os::list_dir -- AFTER -- #: %?",
                     strings.len());
768 769
            strings
        }
770
        #[cfg(windows)]
771
        unsafe fn get_list(p: &Path) -> ~[~str] {
772
            #[fixed_stack_segment]; #[inline(never)];
773
            use libc::consts::os::extra::INVALID_HANDLE_VALUE;
D
Daniel Micay 已提交
774
            use libc::{wcslen, free};
775 776 777 778 779
            use libc::funcs::extra::kernel32::{
                FindFirstFileW,
                FindNextFileW,
                FindClose,
            };
780
            use libc::types::os::arch::extra::HANDLE;
781 782 783
            use os::win32::{
                as_utf16_p
            };
D
Daniel Micay 已提交
784
            use rt::global_heap::malloc_raw;
785

786
            #[nolink]
787
            extern {
788 789
                fn rust_list_dir_wfd_size() -> libc::size_t;
                fn rust_list_dir_wfd_fp_buf(wfd: *libc::c_void) -> *u16;
790 791 792 793
            }
            fn star(p: &Path) -> Path { p.push("*") }
            do as_utf16_p(star(p).to_str()) |path_ptr| {
                let mut strings = ~[];
794
                let wfd_ptr = malloc_raw(rust_list_dir_wfd_size() as uint);
795
                let find_handle = FindFirstFileW(path_ptr, wfd_ptr as HANDLE);
796
                if find_handle as libc::c_int != INVALID_HANDLE_VALUE {
797 798
                    let mut more_files = 1 as libc::c_int;
                    while more_files != 0 {
799
                        let fp_buf = rust_list_dir_wfd_fp_buf(wfd_ptr);
800
                        if fp_buf as uint == 0 {
801
                            fail!("os::list_dir() failure: got null ptr from wfd");
802 803 804 805 806 807 808
                        }
                        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);
                        }
809
                        more_files = FindNextFileW(find_handle, wfd_ptr as HANDLE);
810 811
                    }
                    FindClose(find_handle);
D
Daniel Micay 已提交
812
                    free(wfd_ptr)
813 814 815 816
                }
                strings
            }
        }
817
        do get_list(p).move_iter().filter |filename| {
818 819
            "." != *filename && ".." != *filename
        }.collect()
820 821 822
    }
}

823 824 825 826 827
/**
 * Lists the contents of a directory
 *
 * This version prepends each entry with the directory.
 */
828 829
pub fn list_dir_path(p: &Path) -> ~[Path] {
    list_dir(p).map(|f| p.push(*f))
830 831
}

832 833 834 835
/// 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;
836
    do walk_dir(p) |inner| {
837 838 839 840 841 842 843 844 845 846 847 848
        if !error_happened {
            if path_is_dir(inner) {
                if !remove_dir_recursive(inner) {
                    error_happened = true;
                }
            }
            else {
                if !remove_file(inner) {
                    error_happened = true;
                }
            }
        }
849
        true
850 851 852 853 854
    };
    // Directory should now be empty
    !error_happened && remove_dir(p)
}

855
/// Removes a directory at the specified path
856
pub fn remove_dir(p: &Path) -> bool {
B
Brian Anderson 已提交
857
   return rmdir(p);
858

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

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

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

886
    #[cfg(windows)]
887
    fn chdir(p: &Path) -> bool {
888
        #[fixed_stack_segment]; #[inline(never)];
889 890 891 892 893 894
        unsafe {
            use os::win32::as_utf16_p;
            return do as_utf16_p(p.to_str()) |buf| {
                libc::SetCurrentDirectoryW(buf) != (0 as libc::BOOL)
            };
        }
895 896
    }

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

908
/// Copies a file from one location to another
909
pub fn copy_file(from: &Path, to: &Path) -> bool {
B
Brian Anderson 已提交
910
    return do_copy_file(from, to);
911

912
    #[cfg(windows)]
913
    fn do_copy_file(from: &Path, to: &Path) -> bool {
914
        #[fixed_stack_segment]; #[inline(never)];
915 916 917 918 919 920 921
        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)
                }
922 923 924 925
            }
        }
    }

926
    #[cfg(unix)]
927
    fn do_copy_file(from: &Path, to: &Path) -> bool {
928
        #[fixed_stack_segment]; #[inline(never)];
929
        unsafe {
K
Kevin Ballard 已提交
930 931
            let istream = do from.with_c_str |fromp| {
                do "rb".with_c_str |modebuf| {
932 933 934 935 936
                    libc::fopen(fromp, modebuf)
                }
            };
            if istream as uint == 0u {
                return false;
937
            }
938 939 940 941
            // Preserve permissions
            let from_mode = from.get_mode().expect("copy_file: couldn't get permissions \
                                                    for source file");

K
Kevin Ballard 已提交
942 943
            let ostream = do to.with_c_str |top| {
                do "w+b".with_c_str |modebuf| {
944 945 946 947 948 949
                    libc::fopen(top, modebuf)
                }
            };
            if ostream as uint == 0u {
                fclose(istream);
                return false;
950
            }
951 952 953 954 955
            let bufsize = 8192u;
            let mut buf = vec::with_capacity::<u8>(bufsize);
            let mut done = false;
            let mut ok = true;
            while !done {
956
                do buf.as_mut_buf |b, _sz| {
957 958 959 960 961 962 963 964 965 966
                  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 {
967 968
                      done = true;
                  }
969
              }
970 971 972
            }
            fclose(istream);
            fclose(ostream);
973 974

            // Give the new file the old file's permissions
K
Kevin Ballard 已提交
975
            if do to.with_c_str |to_buf| {
976
                libc::chmod(to_buf, from_mode as libc::mode_t)
J
James Miller 已提交
977 978
            } != 0 {
                return false; // should be a condition...
979
            }
980
            return ok;
981 982 983 984
        }
    }
}

985
/// Deletes an existing file
986
pub fn remove_file(p: &Path) -> bool {
B
Brian Anderson 已提交
987
    return unlink(p);
988

989
    #[cfg(windows)]
990
    fn unlink(p: &Path) -> bool {
991
        #[fixed_stack_segment]; #[inline(never)];
992 993 994 995 996 997
        unsafe {
            use os::win32::as_utf16_p;
            return do as_utf16_p(p.to_str()) |buf| {
                libc::DeleteFileW(buf) != (0 as libc::BOOL)
            };
        }
998 999
    }

1000
    #[cfg(unix)]
1001
    fn unlink(p: &Path) -> bool {
1002
        #[fixed_stack_segment]; #[inline(never)];
1003
        unsafe {
K
Kevin Ballard 已提交
1004
            do p.with_c_str |buf| {
1005
                libc::unlink(buf) == (0 as c_int)
E
Erick Tryzelaar 已提交
1006
            }
1007
        }
1008 1009 1010
    }
}

1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
/// 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)
            }
       }
    }
}

1023
#[cfg(unix)]
1024
/// Returns the platform-specific value of errno
1025 1026 1027 1028
pub fn errno() -> int {
    #[cfg(target_os = "macos")]
    #[cfg(target_os = "freebsd")]
    fn errno_location() -> *c_int {
1029
        #[fixed_stack_segment]; #[inline(never)];
1030 1031
        #[nolink]
        extern {
1032
            fn __error() -> *c_int;
1033 1034 1035 1036 1037 1038 1039 1040 1041
        }
        unsafe {
            __error()
        }
    }

    #[cfg(target_os = "linux")]
    #[cfg(target_os = "android")]
    fn errno_location() -> *c_int {
1042
        #[fixed_stack_segment]; #[inline(never)];
1043 1044
        #[nolink]
        extern {
1045
            fn __errno_location() -> *c_int;
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
        }
        unsafe {
            __errno_location()
        }
    }

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

#[cfg(windows)]
1058
/// Returns the platform-specific value of errno
1059
pub fn errno() -> uint {
1060
    #[fixed_stack_segment]; #[inline(never)];
1061 1062
    use libc::types::os::arch::extra::DWORD;

K
klutzy 已提交
1063
    #[cfg(target_arch = "x86")]
1064 1065
    #[link_name = "kernel32"]
    #[abi = "stdcall"]
1066
    extern "stdcall" {
1067
        fn GetLastError() -> DWORD;
1068 1069
    }

K
klutzy 已提交
1070 1071 1072 1073 1074 1075
    #[cfg(target_arch = "x86_64")]
    #[link_name = "kernel32"]
    extern {
        fn GetLastError() -> DWORD;
    }

1076
    unsafe {
1077
        GetLastError() as uint
1078 1079 1080
    }
}

1081
/// Get a string representing the platform-dependent last error
1082
pub fn last_os_error() -> ~str {
1083 1084 1085 1086 1087
    #[cfg(unix)]
    fn strerror() -> ~str {
        #[cfg(target_os = "macos")]
        #[cfg(target_os = "android")]
        #[cfg(target_os = "freebsd")]
1088 1089
        fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: size_t)
                      -> c_int {
1090 1091
            #[fixed_stack_segment]; #[inline(never)];

1092 1093
            #[nolink]
            extern {
1094 1095
                fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: size_t)
                              -> c_int;
1096 1097 1098 1099 1100 1101 1102 1103
            }
            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 已提交
1104
        // So we just use __xpg_strerror_r which is always POSIX compliant
1105
        #[cfg(target_os = "linux")]
1106
        fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: size_t) -> c_int {
1107
            #[fixed_stack_segment]; #[inline(never)];
1108 1109
            #[nolink]
            extern {
1110 1111 1112 1113
                fn __xpg_strerror_r(errnum: c_int,
                                    buf: *mut c_char,
                                    buflen: size_t)
                                    -> c_int;
1114 1115 1116 1117 1118 1119 1120
            }
            unsafe {
                __xpg_strerror_r(errnum, buf, buflen)
            }
        }

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

1122 1123 1124 1125 1126 1127 1128 1129
        do buf.as_mut_buf |buf, len| {
            unsafe {
                if strerror_r(errno() as c_int, buf, len as size_t) < 0 {
                    fail!("strerror_r failure");
                }

                str::raw::from_c_str(buf as *c_char)
            }
1130
        }
1131
    }
1132 1133 1134

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

1137 1138 1139 1140
        use libc::types::os::arch::extra::DWORD;
        use libc::types::os::arch::extra::LPSTR;
        use libc::types::os::arch::extra::LPVOID;

K
klutzy 已提交
1141
        #[cfg(target_arch = "x86")]
1142 1143
        #[link_name = "kernel32"]
        #[abi = "stdcall"]
1144
        extern "stdcall" {
1145 1146 1147 1148 1149 1150 1151 1152
            fn FormatMessageA(flags: DWORD,
                              lpSrc: LPVOID,
                              msgId: DWORD,
                              langId: DWORD,
                              buf: LPSTR,
                              nsize: DWORD,
                              args: *c_void)
                              -> DWORD;
1153 1154
        }

K
klutzy 已提交
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
        #[cfg(target_arch = "x86_64")]
        #[link_name = "kernel32"]
        extern {
            fn FormatMessageA(flags: DWORD,
                              lpSrc: LPVOID,
                              msgId: DWORD,
                              langId: DWORD,
                              buf: LPSTR,
                              nsize: DWORD,
                              args: *c_void)
                              -> DWORD;
        }

1168 1169
        static FORMAT_MESSAGE_FROM_SYSTEM: DWORD = 0x00001000;
        static FORMAT_MESSAGE_IGNORE_INSERTS: DWORD = 0x00000200;
1170 1171 1172 1173 1174 1175

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

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

1178
        unsafe {
1179
            do buf.as_mut_buf |buf, len| {
1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190
                let res = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM |
                                         FORMAT_MESSAGE_IGNORE_INSERTS,
                                         ptr::mut_null(),
                                         err,
                                         langId,
                                         buf,
                                         len as DWORD,
                                         ptr::null());
                if res == 0 {
                    fail!("[%?] FormatMessage failure", errno());
                }
1191 1192
            }

1193
            do buf.as_imm_buf |buf, _len| {
1194 1195
                str::raw::from_c_str(buf)
            }
1196 1197 1198 1199
        }
    }

    strerror()
1200
}
1201

1202 1203 1204 1205 1206 1207 1208 1209
/**
 * 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
 */
1210
pub fn set_exit_status(code: int) {
1211
    use rt;
1212
    rt::util::set_exit_status(code);
1213
}
1214

1215 1216
unsafe fn load_argc_and_argv(argc: c_int, argv: **c_char) -> ~[~str] {
    let mut args = ~[];
D
Daniel Micay 已提交
1217
    for i in range(0u, argc as uint) {
1218
        args.push(str::raw::from_c_str(*argv.offset(i as int)));
1219
    }
L
Luqman Aden 已提交
1220
    args
1221 1222
}

1223 1224 1225 1226 1227 1228
/**
 * Returns the command line arguments
 *
 * Returns a list of the command line arguments.
 */
#[cfg(target_os = "macos")]
1229
fn real_args() -> ~[~str] {
1230 1231
    #[fixed_stack_segment]; #[inline(never)];

1232
    unsafe {
1233 1234 1235
        let (argc, argv) = (*_NSGetArgc() as c_int,
                            *_NSGetArgv() as **c_char);
        load_argc_and_argv(argc, argv)
1236 1237 1238
    }
}

1239
#[cfg(target_os = "linux")]
K
kyeongwoon 已提交
1240
#[cfg(target_os = "android")]
1241
#[cfg(target_os = "freebsd")]
1242
fn real_args() -> ~[~str] {
1243 1244
    use rt;

1245 1246 1247
    match rt::args::clone() {
        Some(args) => args,
        None => fail!("process arguments not initialized")
1248
    }
1249 1250
}

1251
#[cfg(windows)]
1252
fn real_args() -> ~[~str] {
1253 1254
    #[fixed_stack_segment]; #[inline(never)];

1255
    let mut nArgs: c_int = 0;
D
Daniel Micay 已提交
1256
    let lpArgCount: *mut c_int = &mut nArgs;
T
Tim Chevalier 已提交
1257 1258
    let lpCmdLine = unsafe { GetCommandLineW() };
    let szArgList = unsafe { CommandLineToArgvW(lpCmdLine, lpArgCount) };
1259 1260

    let mut args = ~[];
D
Daniel Micay 已提交
1261
    for i in range(0u, nArgs as uint) {
1262 1263
        unsafe {
            // Determine the length of this argument.
1264
            let ptr = *szArgList.offset(i as int);
1265
            let mut len = 0;
1266
            while *ptr.offset(len as int) != 0 { len += 1; }
1267 1268

            // Push it onto the list.
1269
            args.push(vec::raw::buf_as_slice(ptr, len,
1270
                                             str::from_utf16));
1271 1272 1273 1274
        }
    }

    unsafe {
1275
        LocalFree(szArgList as *c_void);
1276 1277 1278 1279 1280 1281 1282
    }

    return args;
}

type LPCWSTR = *u16;

K
klutzy 已提交
1283
#[cfg(windows, target_arch = "x86")]
1284 1285
#[link_name="kernel32"]
#[abi="stdcall"]
1286
extern "stdcall" {
1287 1288 1289 1290
    fn GetCommandLineW() -> LPCWSTR;
    fn LocalFree(ptr: *c_void);
}

K
klutzy 已提交
1291 1292 1293 1294 1295 1296 1297 1298
#[cfg(windows, target_arch = "x86_64")]
#[link_name="kernel32"]
extern {
    fn GetCommandLineW() -> LPCWSTR;
    fn LocalFree(ptr: *c_void);
}

#[cfg(windows, target_arch = "x86")]
1299 1300
#[link_name="shell32"]
#[abi="stdcall"]
1301
extern "stdcall" {
1302
    fn CommandLineToArgvW(lpCmdLine: LPCWSTR, pNumArgs: *mut c_int) -> **u16;
1303 1304
}

K
klutzy 已提交
1305 1306 1307 1308 1309 1310
#[cfg(windows, target_arch = "x86_64")]
#[link_name="shell32"]
extern {
    fn CommandLineToArgvW(lpCmdLine: LPCWSTR, pNumArgs: *mut c_int) -> **u16;
}

1311 1312 1313 1314
struct OverriddenArgs {
    val: ~[~str]
}

1315 1316
/// Returns the arguments which this program was started with (normally passed
/// via the command line).
1317
pub fn args() -> ~[~str] {
1318
    real_args()
1319 1320
}

1321 1322 1323 1324 1325 1326 1327
#[cfg(target_os = "macos")]
extern {
    // These functions are in crt_externs.h.
    pub fn _NSGetArgc() -> *c_int;
    pub fn _NSGetArgv() -> ***c_char;
}

1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343
// 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 {
1344 1345
    #[fixed_stack_segment]; #[inline(never)];

1346 1347 1348 1349 1350 1351 1352
    unsafe {
        libc::sysconf(libc::_SC_PAGESIZE) as uint
    }
}

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

V
Vadim Chugunov 已提交
1355 1356 1357
    unsafe {
        let mut info = libc::SYSTEM_INFO::new();
        libc::GetSystemInfo(&mut info);
1358

V
Vadim Chugunov 已提交
1359 1360
        return info.dwPageSize as uint;
    }
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
}

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",
            ErrUnknown(code) => fmt!("Unknown error=%?", code),
            ErrUnsupProt => ~"Protection mode unsupported",
            ErrUnsupOffset => ~"Offset in virtual memory mode is unsupported",
            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> {
1424 1425
        #[fixed_stack_segment]; #[inline(never)];

1426 1427 1428 1429 1430 1431 1432 1433 1434
        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 已提交
1435
        for &o in options.iter() {
1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455
            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)
        };
1456
        if r.equiv(&libc::MAP_FAILED) {
1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476
            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())
               }
            })
        }
    }
V
Vadim Chugunov 已提交
1477 1478 1479 1480

    pub fn granularity() -> uint {
        page_size()
    }
1481 1482 1483 1484 1485
}

#[cfg(unix)]
impl Drop for MemoryMap {
    fn drop(&self) {
1486 1487
        #[fixed_stack_segment]; #[inline(never)];

1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503
        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> {
1504 1505
        #[fixed_stack_segment]; #[inline(never)];

1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
        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 已提交
1516
        for &o in options.iter() {
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
            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 {
V
Vadim Chugunov 已提交
1556 1557 1558 1559 1560 1561 1562
            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.
1563 1564 1565 1566 1567 1568
            };
            unsafe {
                let hFile = libc::get_osfhandle(fd) as HANDLE;
                let mapping = libc::CreateFileMappingW(hFile,
                                                       ptr::mut_null(),
                                                       flProtect,
V
Vadim Chugunov 已提交
1569 1570
                                                       0,
                                                       0,
1571 1572 1573 1574 1575 1576 1577 1578 1579
                                                       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 已提交
1580
                                            ((len as u64) >> 32) as DWORD,
1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593
                                            (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)
                    })
                }
            }
        }
    }
V
Vadim Chugunov 已提交
1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606

    /// 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;
        }
    }
1607 1608 1609 1610 1611
}

#[cfg(windows)]
impl Drop for MemoryMap {
    fn drop(&self) {
1612 1613
        #[fixed_stack_segment]; #[inline(never)];

1614
        use libc::types::os::arch::extra::{LPCVOID, HANDLE};
V
Vadim Chugunov 已提交
1615
        use libc::consts::os::extra::FALSE;
1616 1617 1618

        unsafe {
            match self.kind {
V
Vadim Chugunov 已提交
1619 1620 1621 1622 1623 1624
                MapVirtual => {
                    if libc::VirtualFree(self.data as *mut c_void,
                                         self.len,
                                         libc::MEM_RELEASE) == FALSE {
                        error!(fmt!("VirtualFree failed: %?", errno()));
                    }
1625 1626
                },
                MapFile(mapping) => {
V
Vadim Chugunov 已提交
1627
                    if libc::UnmapViewOfFile(self.data as LPCVOID) == FALSE {
1628 1629
                        error!(fmt!("UnmapViewOfFile failed: %?", errno()));
                    }
V
Vadim Chugunov 已提交
1630
                    if libc::CloseHandle(mapping as HANDLE) == FALSE {
1631 1632 1633 1634 1635 1636 1637 1638
                        error!(fmt!("CloseHandle failed: %?", errno()));
                    }
                }
            }
        }
    }
}

1639
pub mod consts {
1640

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

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

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

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

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

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

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

1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681
    #[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 已提交
1682
    pub mod macos {
1683 1684 1685 1686
        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 已提交
1687 1688 1689
    }

    pub mod freebsd {
1690 1691 1692 1693
        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 已提交
1694 1695 1696
    }

    pub mod linux {
1697 1698 1699 1700
        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 已提交
1701
    }
K
kyeongwoon 已提交
1702 1703

    pub mod android {
1704 1705 1706 1707
        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 已提交
1708
    }
1709

I
ILyoan 已提交
1710
    pub mod win32 {
1711 1712 1713 1714
        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 已提交
1715 1716 1717 1718
    }


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

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

1749

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

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

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

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

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

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

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

    #[test]
    fn test_self_exe_path() {
        let path = os::self_exe_path();
P
Patrick Walton 已提交
1814
        assert!(path.is_some());
1815
        let path = path.unwrap();
1816
        debug!(path.clone());
1817 1818

        // Hard to test this function
P
Patrick Walton 已提交
1819
        assert!(path.is_absolute);
1820 1821 1822
    }

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

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

1842
        let mut e = env();
E
Erick Tryzelaar 已提交
1843
        setenv(n, "VALUE");
1844
        assert!(!e.contains(&(n.clone(), ~"VALUE")));
1845 1846

        e = env();
1847
        assert!(e.contains(&(n, ~"VALUE")));
1848 1849
    }

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

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

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

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

E
Erick Tryzelaar 已提交
1865
        setenv("HOME", "/home/MountainView");
1866
        assert_eq!(os::homedir(), Some(Path("/home/MountainView")));
1867

E
Erick Tryzelaar 已提交
1868
        setenv("HOME", "");
P
Patrick Walton 已提交
1869
        assert!(os::homedir().is_none());
1870

D
Daniel Micay 已提交
1871
        for s in oldhome.iter() { setenv("HOME", *s) }
1872 1873 1874
    }

    #[test]
1875
    #[cfg(windows)]
1876 1877
    fn homedir() {

E
Erick Tryzelaar 已提交
1878 1879
        let oldhome = getenv("HOME");
        let olduserprofile = getenv("USERPROFILE");
1880

E
Erick Tryzelaar 已提交
1881 1882
        setenv("HOME", "");
        setenv("USERPROFILE", "");
1883

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

E
Erick Tryzelaar 已提交
1886
        setenv("HOME", "/home/MountainView");
1887
        assert_eq!(os::homedir(), Some(Path("/home/MountainView")));
1888

E
Erick Tryzelaar 已提交
1889
        setenv("HOME", "");
1890

E
Erick Tryzelaar 已提交
1891
        setenv("USERPROFILE", "/home/MountainView");
1892
        assert_eq!(os::homedir(), Some(Path("/home/MountainView")));
1893

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

1898 1899
        oldhome.iter().advance(|s| { setenv("HOME", *s); true });
        olduserprofile.iter().advance(|s| { setenv("USERPROFILE", *s); true });
1900 1901
    }

1902 1903
    #[test]
    fn tmpdir() {
1904
        assert!(!os::tmpdir().to_str().is_empty());
1905 1906
    }

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

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

D
Daniel Micay 已提交
1919
        for dir in dirs.iter() {
1920
            debug!((*dir).clone());
1921
        }
1922 1923
    }

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

1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943
    #[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);
    }


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

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

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

    #[test]
    fn copy_file_ok() {
1966 1967
        #[fixed_stack_segment]; #[inline(never)];

1968
        unsafe {
E
Erick Tryzelaar 已提交
1969 1970 1971 1972 1973
            let tempdir = getcwd(); // would like to use $TMPDIR,
                                    // doesn't seem to work on Linux
            assert!((tempdir.to_str().len() > 0u));
            let input = tempdir.push("in.txt");
            let out = tempdir.push("out.txt");
1974

E
Erick Tryzelaar 已提交
1975
            /* Write the temp input file */
K
Kevin Ballard 已提交
1976 1977
            let ostream = do input.with_c_str |fromp| {
                do "w+b".with_c_str |modebuf| {
1978 1979
                    libc::fopen(fromp, modebuf)
                }
E
Erick Tryzelaar 已提交
1980 1981 1982
            };
            assert!((ostream as uint != 0u));
            let s = ~"hello";
K
Kevin Ballard 已提交
1983
            do "hello".with_c_str |buf| {
1984 1985 1986 1987 1988
                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 已提交
1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001
            }
            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)) {
                fail!("%s doesn't exist", input.to_str());
            }
            assert!((rs));
            let rslt = run::process_status("diff", [input.to_str(), out.to_str()]);
            assert_eq!(rslt, 0);
            assert_eq!(out.get_mode(), in_mode);
            assert!((remove_file(&input)));
            assert!((remove_file(&out)));
2002
        }
2003
    }
2004 2005

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

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

2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037
    #[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() {
2038 2039
        #[fixed_stack_segment]; #[inline(never)];

2040 2041 2042 2043 2044
        use result::{Ok, Err};
        use os::*;
        use libc::*;

        #[cfg(unix)]
2045 2046
        #[fixed_stack_segment]
        #[inline(never)]
2047 2048 2049 2050 2051 2052
        fn lseek_(fd: c_int, size: uint) {
            unsafe {
                assert!(lseek(fd, size as off_t, SEEK_SET) == size as off_t);
            }
        }
        #[cfg(windows)]
2053 2054
        #[fixed_stack_segment]
        #[inline(never)]
2055 2056 2057 2058 2059 2060
        fn lseek_(fd: c_int, size: uint) {
           unsafe {
               assert!(lseek(fd, size as c_long, SEEK_SET) == size as c_long);
           }
        }

E
Erick Tryzelaar 已提交
2061
        let path = tmpdir().push("mmap_file.tmp");
V
Vadim Chugunov 已提交
2062
        let size = MemoryMap::granularity() * 2;
E
Erick Tryzelaar 已提交
2063
        remove_file(&path);
2064 2065

        let fd = unsafe {
K
Kevin Ballard 已提交
2066
            let fd = do path.with_c_str |path| {
2067 2068 2069
                open(path, O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR)
            };
            lseek_(fd, size);
K
Kevin Ballard 已提交
2070
            do "x".with_c_str |x| {
2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092
                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);
        }
    }

2093
    // More recursive_mkdir tests are in extra::tempfile
2094
}