]> git.lizzy.rs Git - rust.git/blob - src/libstd/os.rs
rollup merge of #20264: nagisa/threadrng
[rust.git] / src / libstd / os.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Higher-level interfaces to libc::* functions and operating system services.
12 //!
13 //! In general these take and return rust types, use rust idioms (enums, closures, vectors) rather
14 //! than C idioms, and do more extensive safety checks.
15 //!
16 //! This module is not meant to only contain 1:1 mappings to libc entries; any os-interface code
17 //! that is reasonably useful and broadly applicable can go here. Including utility routines that
18 //! merely build on other os code.
19 //!
20 //! We assume the general case is that users do not care, and do not want to be made to care, which
21 //! operating system they are on. While they may want to special case various special cases -- and
22 //! so we will not _hide_ the facts of which OS the user is on -- they should be given the
23 //! opportunity to write OS-ignorant code by default.
24
25 #![experimental]
26
27 #![allow(missing_docs)]
28 #![allow(non_snake_case)]
29 #![allow(unused_imports)]
30
31 use self::MemoryMapKind::*;
32 use self::MapOption::*;
33 use self::MapError::*;
34
35 use clone::Clone;
36 use error::{FromError, Error};
37 use fmt;
38 use io::{IoResult, IoError};
39 use iter::{Iterator, IteratorExt};
40 use kinds::Copy;
41 use libc::{c_void, c_int, c_char};
42 use libc;
43 use boxed::Box;
44 use ops::{Drop, FnOnce};
45 use option::Option;
46 use option::Option::{Some, None};
47 use path::{Path, GenericPath, BytesContainer};
48 use sys;
49 use sys::os as os_imp;
50 use ptr::PtrExt;
51 use ptr;
52 use result::Result;
53 use result::Result::{Err, Ok};
54 use slice::{AsSlice, SliceExt};
55 use slice::CloneSliceExt;
56 use str::{Str, StrExt};
57 use string::{String, ToString};
58 use sync::atomic::{AtomicInt, INIT_ATOMIC_INT, SeqCst};
59 use vec::Vec;
60
61 #[cfg(unix)] use c_str::ToCStr;
62
63 #[cfg(unix)]
64 pub use sys::ext as unix;
65 #[cfg(windows)]
66 pub use sys::ext as windows;
67
68 /// Get the number of cores available
69 pub fn num_cpus() -> uint {
70     unsafe {
71         return rust_get_num_cpus() as uint;
72     }
73
74     extern {
75         fn rust_get_num_cpus() -> libc::uintptr_t;
76     }
77 }
78
79 pub const TMPBUF_SZ : uint = 1000u;
80
81 /// Returns the current working directory as a `Path`.
82 ///
83 /// # Errors
84 ///
85 /// Returns an `Err` if the current working directory value is invalid.
86 /// Possible cases:
87 ///
88 /// * Current directory does not exist.
89 /// * There are insufficient permissions to access the current directory.
90 /// * The internal buffer is not large enough to hold the path.
91 ///
92 /// # Example
93 ///
94 /// ```rust
95 /// use std::os;
96 ///
97 /// // We assume that we are in a valid directory.
98 /// let current_working_directory = os::getcwd().unwrap();
99 /// println!("The current directory is {}", current_working_directory.display());
100 /// ```
101 pub fn getcwd() -> IoResult<Path> {
102     sys::os::getcwd()
103 }
104
105 /*
106 Accessing environment variables is not generally threadsafe.
107 Serialize access through a global lock.
108 */
109 fn with_env_lock<T, F>(f: F) -> T where
110     F: FnOnce() -> T,
111 {
112     use sync::{StaticMutex, MUTEX_INIT};
113
114     static LOCK: StaticMutex = MUTEX_INIT;
115
116     let _guard = LOCK.lock();
117     f()
118 }
119
120 /// Returns a vector of (variable, value) pairs, for all the environment
121 /// variables of the current process.
122 ///
123 /// Invalid UTF-8 bytes are replaced with \uFFFD. See `String::from_utf8_lossy()`
124 /// for details.
125 ///
126 /// # Example
127 ///
128 /// ```rust
129 /// use std::os;
130 ///
131 /// // We will iterate through the references to the element returned by os::env();
132 /// for &(ref key, ref value) in os::env().iter() {
133 ///     println!("'{}': '{}'", key, value );
134 /// }
135 /// ```
136 pub fn env() -> Vec<(String,String)> {
137     env_as_bytes().into_iter().map(|(k,v)| {
138         let k = String::from_utf8_lossy(k.as_slice()).into_owned();
139         let v = String::from_utf8_lossy(v.as_slice()).into_owned();
140         (k,v)
141     }).collect()
142 }
143
144 /// Returns a vector of (variable, value) byte-vector pairs for all the
145 /// environment variables of the current process.
146 pub fn env_as_bytes() -> Vec<(Vec<u8>,Vec<u8>)> {
147     unsafe {
148         fn env_convert(input: Vec<Vec<u8>>) -> Vec<(Vec<u8>, Vec<u8>)> {
149             let mut pairs = Vec::new();
150             for p in input.iter() {
151                 let mut it = p.splitn(1, |b| *b == b'=');
152                 let key = it.next().unwrap().to_vec();
153                 let default: &[u8] = &[];
154                 let val = it.next().unwrap_or(default).to_vec();
155                 pairs.push((key, val));
156             }
157             pairs
158         }
159         with_env_lock(|| {
160             let unparsed_environ = sys::os::get_env_pairs();
161             env_convert(unparsed_environ)
162         })
163     }
164 }
165
166 #[cfg(unix)]
167 /// Fetches the environment variable `n` from the current process, returning
168 /// None if the variable isn't set.
169 ///
170 /// Any invalid UTF-8 bytes in the value are replaced by \uFFFD. See
171 /// `String::from_utf8_lossy()` for details.
172 ///
173 /// # Panics
174 ///
175 /// Panics if `n` has any interior NULs.
176 ///
177 /// # Example
178 ///
179 /// ```rust
180 /// use std::os;
181 ///
182 /// let key = "HOME";
183 /// match os::getenv(key) {
184 ///     Some(val) => println!("{}: {}", key, val),
185 ///     None => println!("{} is not defined in the environment.", key)
186 /// }
187 /// ```
188 pub fn getenv(n: &str) -> Option<String> {
189     getenv_as_bytes(n).map(|v| String::from_utf8_lossy(v.as_slice()).into_owned())
190 }
191
192 #[cfg(unix)]
193 /// Fetches the environment variable `n` byte vector from the current process,
194 /// returning None if the variable isn't set.
195 ///
196 /// # Panics
197 ///
198 /// Panics if `n` has any interior NULs.
199 pub fn getenv_as_bytes(n: &str) -> Option<Vec<u8>> {
200     use c_str::CString;
201
202     unsafe {
203         with_env_lock(|| {
204             let s = n.with_c_str(|buf| libc::getenv(buf));
205             if s.is_null() {
206                 None
207             } else {
208                 Some(CString::new(s as *const libc::c_char, false).as_bytes_no_nul().to_vec())
209             }
210         })
211     }
212 }
213
214 #[cfg(windows)]
215 /// Fetches the environment variable `n` from the current process, returning
216 /// None if the variable isn't set.
217 pub fn getenv(n: &str) -> Option<String> {
218     unsafe {
219         with_env_lock(|| {
220             use sys::os::fill_utf16_buf_and_decode;
221             let mut n: Vec<u16> = n.utf16_units().collect();
222             n.push(0);
223             fill_utf16_buf_and_decode(|buf, sz| {
224                 libc::GetEnvironmentVariableW(n.as_ptr(), buf, sz)
225             })
226         })
227     }
228 }
229
230 #[cfg(windows)]
231 /// Fetches the environment variable `n` byte vector from the current process,
232 /// returning None if the variable isn't set.
233 pub fn getenv_as_bytes(n: &str) -> Option<Vec<u8>> {
234     getenv(n).map(|s| s.into_bytes())
235 }
236
237 /// Sets the environment variable `n` to the value `v` for the currently running
238 /// process.
239 ///
240 /// # Example
241 ///
242 /// ```rust
243 /// use std::os;
244 ///
245 /// let key = "KEY";
246 /// os::setenv(key, "VALUE");
247 /// match os::getenv(key) {
248 ///     Some(ref val) => println!("{}: {}", key, val),
249 ///     None => println!("{} is not defined in the environment.", key)
250 /// }
251 /// ```
252 pub fn setenv<T: BytesContainer>(n: &str, v: T) {
253     #[cfg(unix)]
254     fn _setenv(n: &str, v: &[u8]) {
255         unsafe {
256             with_env_lock(|| {
257                 n.with_c_str(|nbuf| {
258                     v.with_c_str(|vbuf| {
259                         if libc::funcs::posix01::unistd::setenv(nbuf, vbuf, 1) != 0 {
260                             panic!(IoError::last_error());
261                         }
262                     })
263                 })
264             })
265         }
266     }
267
268     #[cfg(windows)]
269     fn _setenv(n: &str, v: &[u8]) {
270         let mut n: Vec<u16> = n.utf16_units().collect();
271         n.push(0);
272         let mut v: Vec<u16> = ::str::from_utf8(v).unwrap().utf16_units().collect();
273         v.push(0);
274
275         unsafe {
276             with_env_lock(|| {
277                 if libc::SetEnvironmentVariableW(n.as_ptr(), v.as_ptr()) == 0 {
278                     panic!(IoError::last_error());
279                 }
280             })
281         }
282     }
283
284     _setenv(n, v.container_as_bytes())
285 }
286
287 /// Remove a variable from the environment entirely.
288 pub fn unsetenv(n: &str) {
289     #[cfg(unix)]
290     fn _unsetenv(n: &str) {
291         unsafe {
292             with_env_lock(|| {
293                 n.with_c_str(|nbuf| {
294                     if libc::funcs::posix01::unistd::unsetenv(nbuf) != 0 {
295                         panic!(IoError::last_error());
296                     }
297                 })
298             })
299         }
300     }
301
302     #[cfg(windows)]
303     fn _unsetenv(n: &str) {
304         let mut n: Vec<u16> = n.utf16_units().collect();
305         n.push(0);
306         unsafe {
307             with_env_lock(|| {
308                 if libc::SetEnvironmentVariableW(n.as_ptr(), ptr::null()) == 0 {
309                     panic!(IoError::last_error());
310                 }
311             })
312         }
313     }
314
315     _unsetenv(n)
316 }
317
318 /// Parses input according to platform conventions for the `PATH`
319 /// environment variable.
320 ///
321 /// # Example
322 /// ```rust
323 /// use std::os;
324 ///
325 /// let key = "PATH";
326 /// match os::getenv_as_bytes(key) {
327 ///     Some(paths) => {
328 ///         for path in os::split_paths(paths).iter() {
329 ///             println!("'{}'", path.display());
330 ///         }
331 ///     }
332 ///     None => println!("{} is not defined in the environment.", key)
333 /// }
334 /// ```
335 pub fn split_paths<T: BytesContainer>(unparsed: T) -> Vec<Path> {
336     sys::os::split_paths(unparsed.container_as_bytes())
337 }
338
339 /// Joins a collection of `Path`s appropriately for the `PATH`
340 /// environment variable.
341 ///
342 /// Returns a `Vec<u8>` on success, since `Path`s are not utf-8
343 /// encoded on all platforms.
344 ///
345 /// Returns an `Err` (containing an error message) if one of the input
346 /// `Path`s contains an invalid character for constructing the `PATH`
347 /// variable (a double quote on Windows or a colon on Unix).
348 ///
349 /// # Example
350 ///
351 /// ```rust
352 /// use std::os;
353 /// use std::path::Path;
354 ///
355 /// let key = "PATH";
356 /// let mut paths = os::getenv_as_bytes(key).map_or(Vec::new(), os::split_paths);
357 /// paths.push(Path::new("/home/xyz/bin"));
358 /// os::setenv(key, os::join_paths(paths.as_slice()).unwrap());
359 /// ```
360 pub fn join_paths<T: BytesContainer>(paths: &[T]) -> Result<Vec<u8>, &'static str> {
361     sys::os::join_paths(paths)
362 }
363
364 /// A low-level OS in-memory pipe.
365 #[deriving(Copy)]
366 pub struct Pipe {
367     /// A file descriptor representing the reading end of the pipe. Data written
368     /// on the `out` file descriptor can be read from this file descriptor.
369     pub reader: c_int,
370     /// A file descriptor representing the write end of the pipe. Data written
371     /// to this file descriptor can be read from the `input` file descriptor.
372     pub writer: c_int,
373 }
374
375 /// Creates a new low-level OS in-memory pipe.
376 ///
377 /// This function can fail to succeed if there are no more resources available
378 /// to allocate a pipe.
379 ///
380 /// This function is also unsafe as there is no destructor associated with the
381 /// `Pipe` structure will return. If it is not arranged for the returned file
382 /// descriptors to be closed, the file descriptors will leak. For safe handling
383 /// of this scenario, use `std::io::PipeStream` instead.
384 pub unsafe fn pipe() -> IoResult<Pipe> {
385     let (reader, writer) = try!(sys::os::pipe());
386     Ok(Pipe {
387         reader: reader.unwrap(),
388         writer: writer.unwrap(),
389     })
390 }
391
392 /// Returns the proper dll filename for the given basename of a file
393 /// as a String.
394 #[cfg(not(target_os="ios"))]
395 pub fn dll_filename(base: &str) -> String {
396     format!("{}{}{}", consts::DLL_PREFIX, base, consts::DLL_SUFFIX)
397 }
398
399 /// Optionally returns the filesystem path to the current executable which is
400 /// running but with the executable name.
401 ///
402 /// # Examples
403 ///
404 /// ```rust
405 /// use std::os;
406 ///
407 /// match os::self_exe_name() {
408 ///     Some(exe_path) => println!("Path of this executable is: {}", exe_path.display()),
409 ///     None => println!("Unable to get the path of this executable!")
410 /// };
411 /// ```
412 pub fn self_exe_name() -> Option<Path> {
413     sys::os::load_self().and_then(Path::new_opt)
414 }
415
416 /// Optionally returns the filesystem path to the current executable which is
417 /// running.
418 ///
419 /// Like self_exe_name() but without the binary's name.
420 ///
421 /// # Example
422 ///
423 /// ```rust
424 /// use std::os;
425 ///
426 /// match os::self_exe_path() {
427 ///     Some(exe_path) => println!("Executable's Path is: {}", exe_path.display()),
428 ///     None => println!("Impossible to fetch the path of this executable.")
429 /// };
430 /// ```
431 pub fn self_exe_path() -> Option<Path> {
432     self_exe_name().map(|mut p| { p.pop(); p })
433 }
434
435 /// Optionally returns the path to the current user's home directory if known.
436 ///
437 /// # Unix
438 ///
439 /// Returns the value of the 'HOME' environment variable if it is set
440 /// and not equal to the empty string.
441 ///
442 /// # Windows
443 ///
444 /// Returns the value of the 'HOME' environment variable if it is
445 /// set and not equal to the empty string. Otherwise, returns the value of the
446 /// 'USERPROFILE' environment variable if it is set and not equal to the empty
447 /// string.
448 ///
449 /// # Example
450 ///
451 /// ```rust
452 /// use std::os;
453 ///
454 /// match os::homedir() {
455 ///     Some(ref p) => println!("{}", p.display()),
456 ///     None => println!("Impossible to get your home dir!")
457 /// }
458 /// ```
459 pub fn homedir() -> Option<Path> {
460     #[inline]
461     #[cfg(unix)]
462     fn _homedir() -> Option<Path> {
463         aux_homedir("HOME")
464     }
465
466     #[inline]
467     #[cfg(windows)]
468     fn _homedir() -> Option<Path> {
469         aux_homedir("HOME").or(aux_homedir("USERPROFILE"))
470     }
471
472     #[inline]
473     fn aux_homedir(home_name: &str) -> Option<Path> {
474         match getenv_as_bytes(home_name) {
475             Some(p)  => {
476                 if p.is_empty() { None } else { Path::new_opt(p) }
477             },
478             _ => None
479         }
480     }
481     _homedir()
482 }
483
484 /// Returns the path to a temporary directory.
485 ///
486 /// On Unix, returns the value of the 'TMPDIR' environment variable if it is
487 /// set, otherwise for non-Android it returns '/tmp'. If Android, since there
488 /// is no global temporary folder (it is usually allocated per-app), we return
489 /// '/data/local/tmp'.
490 ///
491 /// On Windows, returns the value of, in order, the 'TMP', 'TEMP',
492 /// 'USERPROFILE' environment variable  if any are set and not the empty
493 /// string. Otherwise, tmpdir returns the path to the Windows directory.
494 pub fn tmpdir() -> Path {
495     return lookup();
496
497     fn getenv_nonempty(v: &str) -> Option<Path> {
498         match getenv(v) {
499             Some(x) =>
500                 if x.is_empty() {
501                     None
502                 } else {
503                     Path::new_opt(x)
504                 },
505             _ => None
506         }
507     }
508
509     #[cfg(unix)]
510     fn lookup() -> Path {
511         let default = if cfg!(target_os = "android") {
512             Path::new("/data/local/tmp")
513         } else {
514             Path::new("/tmp")
515         };
516
517         getenv_nonempty("TMPDIR").unwrap_or(default)
518     }
519
520     #[cfg(windows)]
521     fn lookup() -> Path {
522         getenv_nonempty("TMP").or(
523             getenv_nonempty("TEMP").or(
524                 getenv_nonempty("USERPROFILE").or(
525                    getenv_nonempty("WINDIR")))).unwrap_or(Path::new("C:\\Windows"))
526     }
527 }
528
529 /// Convert a relative path to an absolute path
530 ///
531 /// If the given path is relative, return it prepended with the current working
532 /// directory. If the given path is already an absolute path, return it
533 /// as is.
534 ///
535 /// # Example
536 /// ```rust
537 /// use std::os;
538 /// use std::path::Path;
539 ///
540 /// // Assume we're in a path like /home/someuser
541 /// let rel_path = Path::new("..");
542 /// let abs_path = os::make_absolute(&rel_path).unwrap();
543 /// println!("The absolute path is {}", abs_path.display());
544 /// // Prints "The absolute path is /home"
545 /// ```
546 // NB: this is here rather than in path because it is a form of environment
547 // querying; what it does depends on the process working directory, not just
548 // the input paths.
549 pub fn make_absolute(p: &Path) -> IoResult<Path> {
550     if p.is_absolute() {
551         Ok(p.clone())
552     } else {
553         getcwd().map(|mut cwd| {
554             cwd.push(p);
555             cwd
556         })
557     }
558 }
559
560 /// Changes the current working directory to the specified path, returning
561 /// whether the change was completed successfully or not.
562 ///
563 /// # Example
564 /// ```rust
565 /// use std::os;
566 /// use std::path::Path;
567 ///
568 /// let root = Path::new("/");
569 /// assert!(os::change_dir(&root).is_ok());
570 /// println!("Successfully changed working directory to {}!", root.display());
571 /// ```
572 pub fn change_dir(p: &Path) -> IoResult<()> {
573     return sys::os::chdir(p);
574 }
575
576 /// Returns the platform-specific value of errno
577 pub fn errno() -> uint {
578     sys::os::errno() as uint
579 }
580
581 /// Return the string corresponding to an `errno()` value of `errnum`.
582 ///
583 /// # Example
584 /// ```rust
585 /// use std::os;
586 ///
587 /// // Same as println!("{}", last_os_error());
588 /// println!("{}", os::error_string(os::errno() as uint));
589 /// ```
590 pub fn error_string(errnum: uint) -> String {
591     return sys::os::error_string(errnum as i32);
592 }
593
594 /// Get a string representing the platform-dependent last error
595 pub fn last_os_error() -> String {
596     error_string(errno() as uint)
597 }
598
599 static EXIT_STATUS: AtomicInt = INIT_ATOMIC_INT;
600
601 /// Sets the process exit code
602 ///
603 /// Sets the exit code returned by the process if all supervised tasks
604 /// terminate successfully (without panicking). If the current root task panics
605 /// and is supervised by the scheduler then any user-specified exit status is
606 /// ignored and the process exits with the default panic status.
607 ///
608 /// Note that this is not synchronized against modifications of other threads.
609 pub fn set_exit_status(code: int) {
610     EXIT_STATUS.store(code, SeqCst)
611 }
612
613 /// Fetches the process's current exit code. This defaults to 0 and can change
614 /// by calling `set_exit_status`.
615 pub fn get_exit_status() -> int {
616     EXIT_STATUS.load(SeqCst)
617 }
618
619 #[cfg(target_os = "macos")]
620 unsafe fn load_argc_and_argv(argc: int,
621                              argv: *const *const c_char) -> Vec<Vec<u8>> {
622     use c_str::CString;
623
624     Vec::from_fn(argc as uint, |i| {
625         CString::new(*argv.offset(i as int), false).as_bytes_no_nul().to_vec()
626     })
627 }
628
629 /// Returns the command line arguments
630 ///
631 /// Returns a list of the command line arguments.
632 #[cfg(target_os = "macos")]
633 fn real_args_as_bytes() -> Vec<Vec<u8>> {
634     unsafe {
635         let (argc, argv) = (*_NSGetArgc() as int,
636                             *_NSGetArgv() as *const *const c_char);
637         load_argc_and_argv(argc, argv)
638     }
639 }
640
641 // As _NSGetArgc and _NSGetArgv aren't mentioned in iOS docs
642 // and use underscores in their names - they're most probably
643 // are considered private and therefore should be avoided
644 // Here is another way to get arguments using Objective C
645 // runtime
646 //
647 // In general it looks like:
648 // res = Vec::new()
649 // let args = [[NSProcessInfo processInfo] arguments]
650 // for i in range(0, [args count])
651 //      res.push([args objectAtIndex:i])
652 // res
653 #[cfg(target_os = "ios")]
654 fn real_args_as_bytes() -> Vec<Vec<u8>> {
655     use c_str::CString;
656     use iter::range;
657     use mem;
658
659     #[link(name = "objc")]
660     extern {
661         fn sel_registerName(name: *const libc::c_uchar) -> Sel;
662         fn objc_msgSend(obj: NsId, sel: Sel, ...) -> NsId;
663         fn objc_getClass(class_name: *const libc::c_uchar) -> NsId;
664     }
665
666     #[link(name = "Foundation", kind = "framework")]
667     extern {}
668
669     type Sel = *const libc::c_void;
670     type NsId = *const libc::c_void;
671
672     let mut res = Vec::new();
673
674     unsafe {
675         let processInfoSel = sel_registerName("processInfo\0".as_ptr());
676         let argumentsSel = sel_registerName("arguments\0".as_ptr());
677         let utf8Sel = sel_registerName("UTF8String\0".as_ptr());
678         let countSel = sel_registerName("count\0".as_ptr());
679         let objectAtSel = sel_registerName("objectAtIndex:\0".as_ptr());
680
681         let klass = objc_getClass("NSProcessInfo\0".as_ptr());
682         let info = objc_msgSend(klass, processInfoSel);
683         let args = objc_msgSend(info, argumentsSel);
684
685         let cnt: int = mem::transmute(objc_msgSend(args, countSel));
686         for i in range(0, cnt) {
687             let tmp = objc_msgSend(args, objectAtSel, i);
688             let utf_c_str: *const libc::c_char =
689                 mem::transmute(objc_msgSend(tmp, utf8Sel));
690             let s = CString::new(utf_c_str, false);
691             res.push(s.as_bytes_no_nul().to_vec())
692         }
693     }
694
695     res
696 }
697
698 #[cfg(any(target_os = "linux",
699           target_os = "android",
700           target_os = "freebsd",
701           target_os = "dragonfly"))]
702 fn real_args_as_bytes() -> Vec<Vec<u8>> {
703     use rt;
704     rt::args::clone().unwrap_or_else(|| vec![])
705 }
706
707 #[cfg(not(windows))]
708 fn real_args() -> Vec<String> {
709     real_args_as_bytes().into_iter()
710                         .map(|v| {
711                             String::from_utf8_lossy(v.as_slice()).into_owned()
712                         }).collect()
713 }
714
715 #[cfg(windows)]
716 fn real_args() -> Vec<String> {
717     use slice;
718
719     let mut nArgs: c_int = 0;
720     let lpArgCount: *mut c_int = &mut nArgs;
721     let lpCmdLine = unsafe { GetCommandLineW() };
722     let szArgList = unsafe { CommandLineToArgvW(lpCmdLine, lpArgCount) };
723
724     let args = Vec::from_fn(nArgs as uint, |i| unsafe {
725         // Determine the length of this argument.
726         let ptr = *szArgList.offset(i as int);
727         let mut len = 0;
728         while *ptr.offset(len as int) != 0 { len += 1; }
729
730         // Push it onto the list.
731         let ptr = ptr as *const u16;
732         let buf = slice::from_raw_buf(&ptr, len);
733         let opt_s = String::from_utf16(sys::os::truncate_utf16_at_nul(buf));
734         opt_s.expect("CommandLineToArgvW returned invalid UTF-16")
735     });
736
737     unsafe {
738         LocalFree(szArgList as *mut c_void);
739     }
740
741     return args
742 }
743
744 #[cfg(windows)]
745 fn real_args_as_bytes() -> Vec<Vec<u8>> {
746     real_args().into_iter().map(|s| s.into_bytes()).collect()
747 }
748
749 type LPCWSTR = *const u16;
750
751 #[cfg(windows)]
752 #[link_name="kernel32"]
753 extern "system" {
754     fn GetCommandLineW() -> LPCWSTR;
755     fn LocalFree(ptr: *mut c_void);
756 }
757
758 #[cfg(windows)]
759 #[link_name="shell32"]
760 extern "system" {
761     fn CommandLineToArgvW(lpCmdLine: LPCWSTR,
762                           pNumArgs: *mut c_int) -> *mut *mut u16;
763 }
764
765 /// Returns the arguments which this program was started with (normally passed
766 /// via the command line).
767 ///
768 /// The first element is traditionally the path to the executable, but it can be
769 /// set to arbitrary text, and it may not even exist, so this property should not
770 /// be relied upon for security purposes.
771 ///
772 /// The arguments are interpreted as utf-8, with invalid bytes replaced with \uFFFD.
773 /// See `String::from_utf8_lossy` for details.
774 /// # Example
775 ///
776 /// ```rust
777 /// use std::os;
778 ///
779 /// // Prints each argument on a separate line
780 /// for argument in os::args().iter() {
781 ///     println!("{}", argument);
782 /// }
783 /// ```
784 pub fn args() -> Vec<String> {
785     real_args()
786 }
787
788 /// Returns the arguments which this program was started with (normally passed
789 /// via the command line) as byte vectors.
790 pub fn args_as_bytes() -> Vec<Vec<u8>> {
791     real_args_as_bytes()
792 }
793
794 #[cfg(target_os = "macos")]
795 extern {
796     // These functions are in crt_externs.h.
797     pub fn _NSGetArgc() -> *mut c_int;
798     pub fn _NSGetArgv() -> *mut *mut *mut c_char;
799 }
800
801 /// Returns the page size of the current architecture in bytes.
802 pub fn page_size() -> uint {
803     sys::os::page_size()
804 }
805
806 /// A memory mapped file or chunk of memory. This is a very system-specific
807 /// interface to the OS's memory mapping facilities (`mmap` on POSIX,
808 /// `VirtualAlloc`/`CreateFileMapping` on Windows). It makes no attempt at
809 /// abstracting platform differences, besides in error values returned. Consider
810 /// yourself warned.
811 ///
812 /// The memory map is released (unmapped) when the destructor is run, so don't
813 /// let it leave scope by accident if you want it to stick around.
814 #[allow(missing_copy_implementations)]
815 pub struct MemoryMap {
816     data: *mut u8,
817     len: uint,
818     kind: MemoryMapKind,
819 }
820
821 /// Type of memory map
822 pub enum MemoryMapKind {
823     /// Virtual memory map. Usually used to change the permissions of a given
824     /// chunk of memory.  Corresponds to `VirtualAlloc` on Windows.
825     MapFile(*const u8),
826     /// Virtual memory map. Usually used to change the permissions of a given
827     /// chunk of memory, or for allocation. Corresponds to `VirtualAlloc` on
828     /// Windows.
829     MapVirtual
830 }
831
832 impl Copy for MemoryMapKind {}
833
834 /// Options the memory map is created with
835 pub enum MapOption {
836     /// The memory should be readable
837     MapReadable,
838     /// The memory should be writable
839     MapWritable,
840     /// The memory should be executable
841     MapExecutable,
842     /// Create a map for a specific address range. Corresponds to `MAP_FIXED` on
843     /// POSIX.
844     MapAddr(*const u8),
845     /// Create a memory mapping for a file with a given HANDLE.
846     #[cfg(windows)]
847     MapFd(libc::HANDLE),
848     /// Create a memory mapping for a file with a given fd.
849     #[cfg(not(windows))]
850     MapFd(c_int),
851     /// When using `MapFd`, the start of the map is `uint` bytes from the start
852     /// of the file.
853     MapOffset(uint),
854     /// On POSIX, this can be used to specify the default flags passed to
855     /// `mmap`. By default it uses `MAP_PRIVATE` and, if not using `MapFd`,
856     /// `MAP_ANON`. This will override both of those. This is platform-specific
857     /// (the exact values used) and ignored on Windows.
858     MapNonStandardFlags(c_int),
859 }
860
861 impl Copy for MapOption {}
862
863 /// Possible errors when creating a map.
864 #[deriving(Copy)]
865 pub enum MapError {
866     /// # The following are POSIX-specific
867     ///
868     /// fd was not open for reading or, if using `MapWritable`, was not open for
869     /// writing.
870     ErrFdNotAvail,
871     /// fd was not valid
872     ErrInvalidFd,
873     /// Either the address given by `MapAddr` or offset given by `MapOffset` was
874     /// not a multiple of `MemoryMap::granularity` (unaligned to page size).
875     ErrUnaligned,
876     /// With `MapFd`, the fd does not support mapping.
877     ErrNoMapSupport,
878     /// If using `MapAddr`, the address + `min_len` was outside of the process's
879     /// address space. If using `MapFd`, the target of the fd didn't have enough
880     /// resources to fulfill the request.
881     ErrNoMem,
882     /// A zero-length map was requested. This is invalid according to
883     /// [POSIX](http://pubs.opengroup.org/onlinepubs/9699919799/functions/mmap.html).
884     /// Not all platforms obey this, but this wrapper does.
885     ErrZeroLength,
886     /// Unrecognized error. The inner value is the unrecognized errno.
887     ErrUnknown(int),
888     /// # The following are Windows-specific
889     ///
890     /// Unsupported combination of protection flags
891     /// (`MapReadable`/`MapWritable`/`MapExecutable`).
892     ErrUnsupProt,
893     /// When using `MapFd`, `MapOffset` was given (Windows does not support this
894     /// at all)
895     ErrUnsupOffset,
896     /// When using `MapFd`, there was already a mapping to the file.
897     ErrAlreadyExists,
898     /// Unrecognized error from `VirtualAlloc`. The inner value is the return
899     /// value of GetLastError.
900     ErrVirtualAlloc(uint),
901     /// Unrecognized error from `CreateFileMapping`. The inner value is the
902     /// return value of `GetLastError`.
903     ErrCreateFileMappingW(uint),
904     /// Unrecognized error from `MapViewOfFile`. The inner value is the return
905     /// value of `GetLastError`.
906     ErrMapViewOfFile(uint)
907 }
908
909 impl fmt::Show for MapError {
910     fn fmt(&self, out: &mut fmt::Formatter) -> fmt::Result {
911         let str = match *self {
912             ErrFdNotAvail => "fd not available for reading or writing",
913             ErrInvalidFd => "Invalid fd",
914             ErrUnaligned => {
915                 "Unaligned address, invalid flags, negative length or \
916                  unaligned offset"
917             }
918             ErrNoMapSupport=> "File doesn't support mapping",
919             ErrNoMem => "Invalid address, or not enough available memory",
920             ErrUnsupProt => "Protection mode unsupported",
921             ErrUnsupOffset => "Offset in virtual memory mode is unsupported",
922             ErrAlreadyExists => "File mapping for specified file already exists",
923             ErrZeroLength => "Zero-length mapping not allowed",
924             ErrUnknown(code) => {
925                 return write!(out, "Unknown error = {}", code)
926             },
927             ErrVirtualAlloc(code) => {
928                 return write!(out, "VirtualAlloc failure = {}", code)
929             },
930             ErrCreateFileMappingW(code) => {
931                 return write!(out, "CreateFileMappingW failure = {}", code)
932             },
933             ErrMapViewOfFile(code) => {
934                 return write!(out, "MapViewOfFile failure = {}", code)
935             }
936         };
937         write!(out, "{}", str)
938     }
939 }
940
941 impl Error for MapError {
942     fn description(&self) -> &str { "memory map error" }
943     fn detail(&self) -> Option<String> { Some(self.to_string()) }
944 }
945
946 impl FromError<MapError> for Box<Error> {
947     fn from_error(err: MapError) -> Box<Error> {
948         box err
949     }
950 }
951
952 // Round up `from` to be divisible by `to`
953 fn round_up(from: uint, to: uint) -> uint {
954     let r = if from % to == 0 {
955         from
956     } else {
957         from + to - (from % to)
958     };
959     if r == 0 {
960         to
961     } else {
962         r
963     }
964 }
965
966 #[cfg(unix)]
967 impl MemoryMap {
968     /// Create a new mapping with the given `options`, at least `min_len` bytes
969     /// long. `min_len` must be greater than zero; see the note on
970     /// `ErrZeroLength`.
971     pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
972         use libc::off_t;
973
974         if min_len == 0 {
975             return Err(ErrZeroLength)
976         }
977         let mut addr: *const u8 = ptr::null();
978         let mut prot = 0;
979         let mut flags = libc::MAP_PRIVATE;
980         let mut fd = -1;
981         let mut offset = 0;
982         let mut custom_flags = false;
983         let len = round_up(min_len, page_size());
984
985         for &o in options.iter() {
986             match o {
987                 MapReadable => { prot |= libc::PROT_READ; },
988                 MapWritable => { prot |= libc::PROT_WRITE; },
989                 MapExecutable => { prot |= libc::PROT_EXEC; },
990                 MapAddr(addr_) => {
991                     flags |= libc::MAP_FIXED;
992                     addr = addr_;
993                 },
994                 MapFd(fd_) => {
995                     flags |= libc::MAP_FILE;
996                     fd = fd_;
997                 },
998                 MapOffset(offset_) => { offset = offset_ as off_t; },
999                 MapNonStandardFlags(f) => { custom_flags = true; flags = f },
1000             }
1001         }
1002         if fd == -1 && !custom_flags { flags |= libc::MAP_ANON; }
1003
1004         let r = unsafe {
1005             libc::mmap(addr as *mut c_void, len as libc::size_t, prot, flags,
1006                        fd, offset)
1007         };
1008         if r == libc::MAP_FAILED {
1009             Err(match errno() as c_int {
1010                 libc::EACCES => ErrFdNotAvail,
1011                 libc::EBADF => ErrInvalidFd,
1012                 libc::EINVAL => ErrUnaligned,
1013                 libc::ENODEV => ErrNoMapSupport,
1014                 libc::ENOMEM => ErrNoMem,
1015                 code => ErrUnknown(code as int)
1016             })
1017         } else {
1018             Ok(MemoryMap {
1019                data: r as *mut u8,
1020                len: len,
1021                kind: if fd == -1 {
1022                    MapVirtual
1023                } else {
1024                    MapFile(ptr::null())
1025                }
1026             })
1027         }
1028     }
1029
1030     /// Granularity that the offset or address must be for `MapOffset` and
1031     /// `MapAddr` respectively.
1032     pub fn granularity() -> uint {
1033         page_size()
1034     }
1035 }
1036
1037 #[cfg(unix)]
1038 impl Drop for MemoryMap {
1039     /// Unmap the mapping. Panics the task if `munmap` panics.
1040     fn drop(&mut self) {
1041         if self.len == 0 { /* workaround for dummy_stack */ return; }
1042
1043         unsafe {
1044             // `munmap` only panics due to logic errors
1045             libc::munmap(self.data as *mut c_void, self.len as libc::size_t);
1046         }
1047     }
1048 }
1049
1050 #[cfg(windows)]
1051 impl MemoryMap {
1052     /// Create a new mapping with the given `options`, at least `min_len` bytes long.
1053     pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
1054         use libc::types::os::arch::extra::{LPVOID, DWORD, SIZE_T, HANDLE};
1055
1056         let mut lpAddress: LPVOID = ptr::null_mut();
1057         let mut readable = false;
1058         let mut writable = false;
1059         let mut executable = false;
1060         let mut handle: HANDLE = libc::INVALID_HANDLE_VALUE;
1061         let mut offset: uint = 0;
1062         let len = round_up(min_len, page_size());
1063
1064         for &o in options.iter() {
1065             match o {
1066                 MapReadable => { readable = true; },
1067                 MapWritable => { writable = true; },
1068                 MapExecutable => { executable = true; }
1069                 MapAddr(addr_) => { lpAddress = addr_ as LPVOID; },
1070                 MapFd(handle_) => { handle = handle_; },
1071                 MapOffset(offset_) => { offset = offset_; },
1072                 MapNonStandardFlags(..) => {}
1073             }
1074         }
1075
1076         let flProtect = match (executable, readable, writable) {
1077             (false, false, false) if handle == libc::INVALID_HANDLE_VALUE => libc::PAGE_NOACCESS,
1078             (false, true, false) => libc::PAGE_READONLY,
1079             (false, true, true) => libc::PAGE_READWRITE,
1080             (true, false, false) if handle == libc::INVALID_HANDLE_VALUE => libc::PAGE_EXECUTE,
1081             (true, true, false) => libc::PAGE_EXECUTE_READ,
1082             (true, true, true) => libc::PAGE_EXECUTE_READWRITE,
1083             _ => return Err(ErrUnsupProt)
1084         };
1085
1086         if handle == libc::INVALID_HANDLE_VALUE {
1087             if offset != 0 {
1088                 return Err(ErrUnsupOffset);
1089             }
1090             let r = unsafe {
1091                 libc::VirtualAlloc(lpAddress,
1092                                    len as SIZE_T,
1093                                    libc::MEM_COMMIT | libc::MEM_RESERVE,
1094                                    flProtect)
1095             };
1096             match r as uint {
1097                 0 => Err(ErrVirtualAlloc(errno())),
1098                 _ => Ok(MemoryMap {
1099                    data: r as *mut u8,
1100                    len: len,
1101                    kind: MapVirtual
1102                 })
1103             }
1104         } else {
1105             let dwDesiredAccess = match (executable, readable, writable) {
1106                 (false, true, false) => libc::FILE_MAP_READ,
1107                 (false, true, true) => libc::FILE_MAP_WRITE,
1108                 (true, true, false) => libc::FILE_MAP_READ | libc::FILE_MAP_EXECUTE,
1109                 (true, true, true) => libc::FILE_MAP_WRITE | libc::FILE_MAP_EXECUTE,
1110                 _ => return Err(ErrUnsupProt) // Actually, because of the check above,
1111                                               // we should never get here.
1112             };
1113             unsafe {
1114                 let hFile = handle;
1115                 let mapping = libc::CreateFileMappingW(hFile,
1116                                                        ptr::null_mut(),
1117                                                        flProtect,
1118                                                        0,
1119                                                        0,
1120                                                        ptr::null());
1121                 if mapping == ptr::null_mut() {
1122                     return Err(ErrCreateFileMappingW(errno()));
1123                 }
1124                 if errno() as c_int == libc::ERROR_ALREADY_EXISTS {
1125                     return Err(ErrAlreadyExists);
1126                 }
1127                 let r = libc::MapViewOfFile(mapping,
1128                                             dwDesiredAccess,
1129                                             ((len as u64) >> 32) as DWORD,
1130                                             (offset & 0xffff_ffff) as DWORD,
1131                                             0);
1132                 match r as uint {
1133                     0 => Err(ErrMapViewOfFile(errno())),
1134                     _ => Ok(MemoryMap {
1135                        data: r as *mut u8,
1136                        len: len,
1137                        kind: MapFile(mapping as *const u8)
1138                     })
1139                 }
1140             }
1141         }
1142     }
1143
1144     /// Granularity of MapAddr() and MapOffset() parameter values.
1145     /// This may be greater than the value returned by page_size().
1146     pub fn granularity() -> uint {
1147         use mem;
1148         unsafe {
1149             let mut info = mem::zeroed();
1150             libc::GetSystemInfo(&mut info);
1151
1152             return info.dwAllocationGranularity as uint;
1153         }
1154     }
1155 }
1156
1157 #[cfg(windows)]
1158 impl Drop for MemoryMap {
1159     /// Unmap the mapping. Panics the task if any of `VirtualFree`,
1160     /// `UnmapViewOfFile`, or `CloseHandle` fail.
1161     fn drop(&mut self) {
1162         use libc::types::os::arch::extra::{LPCVOID, HANDLE};
1163         use libc::consts::os::extra::FALSE;
1164         if self.len == 0 { return }
1165
1166         unsafe {
1167             match self.kind {
1168                 MapVirtual => {
1169                     if libc::VirtualFree(self.data as *mut c_void, 0,
1170                                          libc::MEM_RELEASE) == 0 {
1171                         println!("VirtualFree failed: {}", errno());
1172                     }
1173                 },
1174                 MapFile(mapping) => {
1175                     if libc::UnmapViewOfFile(self.data as LPCVOID) == FALSE {
1176                         println!("UnmapViewOfFile failed: {}", errno());
1177                     }
1178                     if libc::CloseHandle(mapping as HANDLE) == FALSE {
1179                         println!("CloseHandle failed: {}", errno());
1180                     }
1181                 }
1182             }
1183         }
1184     }
1185 }
1186
1187 impl MemoryMap {
1188     /// Returns the pointer to the memory created or modified by this map.
1189     pub fn data(&self) -> *mut u8 { self.data }
1190     /// Returns the number of bytes this map applies to.
1191     pub fn len(&self) -> uint { self.len }
1192     /// Returns the type of mapping this represents.
1193     pub fn kind(&self) -> MemoryMapKind { self.kind }
1194 }
1195
1196 #[cfg(target_os = "linux")]
1197 pub mod consts {
1198     pub use os::arch_consts::ARCH;
1199
1200     pub const FAMILY: &'static str = "unix";
1201
1202     /// A string describing the specific operating system in use: in this
1203     /// case, `linux`.
1204     pub const SYSNAME: &'static str = "linux";
1205
1206     /// Specifies the filename prefix used for shared libraries on this
1207     /// platform: in this case, `lib`.
1208     pub const DLL_PREFIX: &'static str = "lib";
1209
1210     /// Specifies the filename suffix used for shared libraries on this
1211     /// platform: in this case, `.so`.
1212     pub const DLL_SUFFIX: &'static str = ".so";
1213
1214     /// Specifies the file extension used for shared libraries on this
1215     /// platform that goes after the dot: in this case, `so`.
1216     pub const DLL_EXTENSION: &'static str = "so";
1217
1218     /// Specifies the filename suffix used for executable binaries on this
1219     /// platform: in this case, the empty string.
1220     pub const EXE_SUFFIX: &'static str = "";
1221
1222     /// Specifies the file extension, if any, used for executable binaries
1223     /// on this platform: in this case, the empty string.
1224     pub const EXE_EXTENSION: &'static str = "";
1225 }
1226
1227 #[cfg(target_os = "macos")]
1228 pub mod consts {
1229     pub use os::arch_consts::ARCH;
1230
1231     pub const FAMILY: &'static str = "unix";
1232
1233     /// A string describing the specific operating system in use: in this
1234     /// case, `macos`.
1235     pub const SYSNAME: &'static str = "macos";
1236
1237     /// Specifies the filename prefix used for shared libraries on this
1238     /// platform: in this case, `lib`.
1239     pub const DLL_PREFIX: &'static str = "lib";
1240
1241     /// Specifies the filename suffix used for shared libraries on this
1242     /// platform: in this case, `.dylib`.
1243     pub const DLL_SUFFIX: &'static str = ".dylib";
1244
1245     /// Specifies the file extension used for shared libraries on this
1246     /// platform that goes after the dot: in this case, `dylib`.
1247     pub const DLL_EXTENSION: &'static str = "dylib";
1248
1249     /// Specifies the filename suffix used for executable binaries on this
1250     /// platform: in this case, the empty string.
1251     pub const EXE_SUFFIX: &'static str = "";
1252
1253     /// Specifies the file extension, if any, used for executable binaries
1254     /// on this platform: in this case, the empty string.
1255     pub const EXE_EXTENSION: &'static str = "";
1256 }
1257
1258 #[cfg(target_os = "ios")]
1259 pub mod consts {
1260     pub use os::arch_consts::ARCH;
1261
1262     pub const FAMILY: &'static str = "unix";
1263
1264     /// A string describing the specific operating system in use: in this
1265     /// case, `ios`.
1266     pub const SYSNAME: &'static str = "ios";
1267
1268     /// Specifies the filename suffix used for executable binaries on this
1269     /// platform: in this case, the empty string.
1270     pub const EXE_SUFFIX: &'static str = "";
1271
1272     /// Specifies the file extension, if any, used for executable binaries
1273     /// on this platform: in this case, the empty string.
1274     pub const EXE_EXTENSION: &'static str = "";
1275 }
1276
1277 #[cfg(target_os = "freebsd")]
1278 pub mod consts {
1279     pub use os::arch_consts::ARCH;
1280
1281     pub const FAMILY: &'static str = "unix";
1282
1283     /// A string describing the specific operating system in use: in this
1284     /// case, `freebsd`.
1285     pub const SYSNAME: &'static str = "freebsd";
1286
1287     /// Specifies the filename prefix used for shared libraries on this
1288     /// platform: in this case, `lib`.
1289     pub const DLL_PREFIX: &'static str = "lib";
1290
1291     /// Specifies the filename suffix used for shared libraries on this
1292     /// platform: in this case, `.so`.
1293     pub const DLL_SUFFIX: &'static str = ".so";
1294
1295     /// Specifies the file extension used for shared libraries on this
1296     /// platform that goes after the dot: in this case, `so`.
1297     pub const DLL_EXTENSION: &'static str = "so";
1298
1299     /// Specifies the filename suffix used for executable binaries on this
1300     /// platform: in this case, the empty string.
1301     pub const EXE_SUFFIX: &'static str = "";
1302
1303     /// Specifies the file extension, if any, used for executable binaries
1304     /// on this platform: in this case, the empty string.
1305     pub const EXE_EXTENSION: &'static str = "";
1306 }
1307
1308 #[cfg(target_os = "dragonfly")]
1309 pub mod consts {
1310     pub use os::arch_consts::ARCH;
1311
1312     pub const FAMILY: &'static str = "unix";
1313
1314     /// A string describing the specific operating system in use: in this
1315     /// case, `dragonfly`.
1316     pub const SYSNAME: &'static str = "dragonfly";
1317
1318     /// Specifies the filename prefix used for shared libraries on this
1319     /// platform: in this case, `lib`.
1320     pub const DLL_PREFIX: &'static str = "lib";
1321
1322     /// Specifies the filename suffix used for shared libraries on this
1323     /// platform: in this case, `.so`.
1324     pub const DLL_SUFFIX: &'static str = ".so";
1325
1326     /// Specifies the file extension used for shared libraries on this
1327     /// platform that goes after the dot: in this case, `so`.
1328     pub const DLL_EXTENSION: &'static str = "so";
1329
1330     /// Specifies the filename suffix used for executable binaries on this
1331     /// platform: in this case, the empty string.
1332     pub const EXE_SUFFIX: &'static str = "";
1333
1334     /// Specifies the file extension, if any, used for executable binaries
1335     /// on this platform: in this case, the empty string.
1336     pub const EXE_EXTENSION: &'static str = "";
1337 }
1338
1339 #[cfg(target_os = "android")]
1340 pub mod consts {
1341     pub use os::arch_consts::ARCH;
1342
1343     pub const FAMILY: &'static str = "unix";
1344
1345     /// A string describing the specific operating system in use: in this
1346     /// case, `android`.
1347     pub const SYSNAME: &'static str = "android";
1348
1349     /// Specifies the filename prefix used for shared libraries on this
1350     /// platform: in this case, `lib`.
1351     pub const DLL_PREFIX: &'static str = "lib";
1352
1353     /// Specifies the filename suffix used for shared libraries on this
1354     /// platform: in this case, `.so`.
1355     pub const DLL_SUFFIX: &'static str = ".so";
1356
1357     /// Specifies the file extension used for shared libraries on this
1358     /// platform that goes after the dot: in this case, `so`.
1359     pub const DLL_EXTENSION: &'static str = "so";
1360
1361     /// Specifies the filename suffix used for executable binaries on this
1362     /// platform: in this case, the empty string.
1363     pub const EXE_SUFFIX: &'static str = "";
1364
1365     /// Specifies the file extension, if any, used for executable binaries
1366     /// on this platform: in this case, the empty string.
1367     pub const EXE_EXTENSION: &'static str = "";
1368 }
1369
1370 #[cfg(target_os = "windows")]
1371 pub mod consts {
1372     pub use os::arch_consts::ARCH;
1373
1374     pub const FAMILY: &'static str = "windows";
1375
1376     /// A string describing the specific operating system in use: in this
1377     /// case, `windows`.
1378     pub const SYSNAME: &'static str = "windows";
1379
1380     /// Specifies the filename prefix used for shared libraries on this
1381     /// platform: in this case, the empty string.
1382     pub const DLL_PREFIX: &'static str = "";
1383
1384     /// Specifies the filename suffix used for shared libraries on this
1385     /// platform: in this case, `.dll`.
1386     pub const DLL_SUFFIX: &'static str = ".dll";
1387
1388     /// Specifies the file extension used for shared libraries on this
1389     /// platform that goes after the dot: in this case, `dll`.
1390     pub const DLL_EXTENSION: &'static str = "dll";
1391
1392     /// Specifies the filename suffix used for executable binaries on this
1393     /// platform: in this case, `.exe`.
1394     pub const EXE_SUFFIX: &'static str = ".exe";
1395
1396     /// Specifies the file extension, if any, used for executable binaries
1397     /// on this platform: in this case, `exe`.
1398     pub const EXE_EXTENSION: &'static str = "exe";
1399 }
1400
1401 #[cfg(target_arch = "x86")]
1402 mod arch_consts {
1403     pub const ARCH: &'static str = "x86";
1404 }
1405
1406 #[cfg(target_arch = "x86_64")]
1407 mod arch_consts {
1408     pub const ARCH: &'static str = "x86_64";
1409 }
1410
1411 #[cfg(target_arch = "arm")]
1412 mod arch_consts {
1413     pub const ARCH: &'static str = "arm";
1414 }
1415
1416 #[cfg(target_arch = "mips")]
1417 mod arch_consts {
1418     pub const ARCH: &'static str = "mips";
1419 }
1420
1421 #[cfg(target_arch = "mipsel")]
1422 mod arch_consts {
1423     pub const ARCH: &'static str = "mipsel";
1424 }
1425
1426 #[cfg(test)]
1427 mod tests {
1428     use prelude::*;
1429     use option;
1430     use os::{env, getcwd, getenv, make_absolute};
1431     use os::{split_paths, join_paths, setenv, unsetenv};
1432     use os;
1433     use rand::Rng;
1434     use rand;
1435
1436     #[test]
1437     pub fn last_os_error() {
1438         debug!("{}", os::last_os_error());
1439     }
1440
1441     fn make_rand_name() -> String {
1442         let mut rng = rand::thread_rng();
1443         let n = format!("TEST{}", rng.gen_ascii_chars().take(10u)
1444                                      .collect::<String>());
1445         assert!(getenv(n.as_slice()).is_none());
1446         n
1447     }
1448
1449     #[test]
1450     fn test_num_cpus() {
1451         assert!(os::num_cpus() > 0);
1452     }
1453
1454     #[test]
1455     fn test_setenv() {
1456         let n = make_rand_name();
1457         setenv(n.as_slice(), "VALUE");
1458         assert_eq!(getenv(n.as_slice()), option::Option::Some("VALUE".to_string()));
1459     }
1460
1461     #[test]
1462     fn test_unsetenv() {
1463         let n = make_rand_name();
1464         setenv(n.as_slice(), "VALUE");
1465         unsetenv(n.as_slice());
1466         assert_eq!(getenv(n.as_slice()), option::Option::None);
1467     }
1468
1469     #[test]
1470     #[ignore]
1471     fn test_setenv_overwrite() {
1472         let n = make_rand_name();
1473         setenv(n.as_slice(), "1");
1474         setenv(n.as_slice(), "2");
1475         assert_eq!(getenv(n.as_slice()), option::Option::Some("2".to_string()));
1476         setenv(n.as_slice(), "");
1477         assert_eq!(getenv(n.as_slice()), option::Option::Some("".to_string()));
1478     }
1479
1480     // Windows GetEnvironmentVariable requires some extra work to make sure
1481     // the buffer the variable is copied into is the right size
1482     #[test]
1483     #[ignore]
1484     fn test_getenv_big() {
1485         let mut s = "".to_string();
1486         let mut i = 0i;
1487         while i < 100 {
1488             s.push_str("aaaaaaaaaa");
1489             i += 1;
1490         }
1491         let n = make_rand_name();
1492         setenv(n.as_slice(), s.as_slice());
1493         debug!("{}", s.clone());
1494         assert_eq!(getenv(n.as_slice()), option::Option::Some(s));
1495     }
1496
1497     #[test]
1498     fn test_self_exe_name() {
1499         let path = os::self_exe_name();
1500         assert!(path.is_some());
1501         let path = path.unwrap();
1502         debug!("{}", path.display());
1503
1504         // Hard to test this function
1505         assert!(path.is_absolute());
1506     }
1507
1508     #[test]
1509     fn test_self_exe_path() {
1510         let path = os::self_exe_path();
1511         assert!(path.is_some());
1512         let path = path.unwrap();
1513         debug!("{}", path.display());
1514
1515         // Hard to test this function
1516         assert!(path.is_absolute());
1517     }
1518
1519     #[test]
1520     #[ignore]
1521     fn test_env_getenv() {
1522         let e = env();
1523         assert!(e.len() > 0u);
1524         for p in e.iter() {
1525             let (n, v) = (*p).clone();
1526             debug!("{}", n);
1527             let v2 = getenv(n.as_slice());
1528             // MingW seems to set some funky environment variables like
1529             // "=C:=C:\MinGW\msys\1.0\bin" and "!::=::\" that are returned
1530             // from env() but not visible from getenv().
1531             assert!(v2.is_none() || v2 == option::Option::Some(v));
1532         }
1533     }
1534
1535     #[test]
1536     fn test_env_set_get_huge() {
1537         let n = make_rand_name();
1538         let s = "x".repeat(10000).to_string();
1539         setenv(n.as_slice(), s.as_slice());
1540         assert_eq!(getenv(n.as_slice()), Some(s));
1541         unsetenv(n.as_slice());
1542         assert_eq!(getenv(n.as_slice()), None);
1543     }
1544
1545     #[test]
1546     fn test_env_setenv() {
1547         let n = make_rand_name();
1548
1549         let mut e = env();
1550         setenv(n.as_slice(), "VALUE");
1551         assert!(!e.contains(&(n.clone(), "VALUE".to_string())));
1552
1553         e = env();
1554         assert!(e.contains(&(n, "VALUE".to_string())));
1555     }
1556
1557     #[test]
1558     fn test() {
1559         assert!((!Path::new("test-path").is_absolute()));
1560
1561         let cwd = getcwd().unwrap();
1562         debug!("Current working directory: {}", cwd.display());
1563
1564         debug!("{}", make_absolute(&Path::new("test-path")).unwrap().display());
1565         debug!("{}", make_absolute(&Path::new("/usr/bin")).unwrap().display());
1566     }
1567
1568     #[test]
1569     #[cfg(unix)]
1570     fn homedir() {
1571         let oldhome = getenv("HOME");
1572
1573         setenv("HOME", "/home/MountainView");
1574         assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1575
1576         setenv("HOME", "");
1577         assert!(os::homedir().is_none());
1578
1579         for s in oldhome.iter() {
1580             setenv("HOME", s.as_slice());
1581         }
1582     }
1583
1584     #[test]
1585     #[cfg(windows)]
1586     fn homedir() {
1587
1588         let oldhome = getenv("HOME");
1589         let olduserprofile = getenv("USERPROFILE");
1590
1591         setenv("HOME", "");
1592         setenv("USERPROFILE", "");
1593
1594         assert!(os::homedir().is_none());
1595
1596         setenv("HOME", "/home/MountainView");
1597         assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1598
1599         setenv("HOME", "");
1600
1601         setenv("USERPROFILE", "/home/MountainView");
1602         assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1603
1604         setenv("HOME", "/home/MountainView");
1605         setenv("USERPROFILE", "/home/PaloAlto");
1606         assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1607
1608         for s in oldhome.iter() {
1609             setenv("HOME", s.as_slice());
1610         }
1611         for s in olduserprofile.iter() {
1612             setenv("USERPROFILE", s.as_slice());
1613         }
1614     }
1615
1616     #[test]
1617     fn memory_map_rw() {
1618         use result::Result::{Ok, Err};
1619
1620         let chunk = match os::MemoryMap::new(16, &[
1621             os::MapOption::MapReadable,
1622             os::MapOption::MapWritable
1623         ]) {
1624             Ok(chunk) => chunk,
1625             Err(msg) => panic!("{}", msg)
1626         };
1627         assert!(chunk.len >= 16);
1628
1629         unsafe {
1630             *chunk.data = 0xBE;
1631             assert!(*chunk.data == 0xBE);
1632         }
1633     }
1634
1635     #[test]
1636     fn memory_map_file() {
1637         use libc;
1638         use os::*;
1639         use io::fs::{File, unlink};
1640         use io::SeekStyle::SeekSet;
1641         use io::FileMode::Open;
1642         use io::FileAccess::ReadWrite;
1643
1644         #[cfg(not(windows))]
1645         fn get_fd(file: &File) -> libc::c_int {
1646             use os::unix::AsRawFd;
1647             file.as_raw_fd()
1648         }
1649
1650         #[cfg(windows)]
1651         fn get_fd(file: &File) -> libc::HANDLE {
1652             use os::windows::AsRawHandle;
1653             file.as_raw_handle()
1654         }
1655
1656         let mut path = tmpdir();
1657         path.push("mmap_file.tmp");
1658         let size = MemoryMap::granularity() * 2;
1659         let mut file = File::open_mode(&path, Open, ReadWrite).unwrap();
1660         file.seek(size as i64, SeekSet);
1661         file.write_u8(0);
1662
1663         let chunk = MemoryMap::new(size / 2, &[
1664             MapOption::MapReadable,
1665             MapOption::MapWritable,
1666             MapOption::MapFd(get_fd(&file)),
1667             MapOption::MapOffset(size / 2)
1668         ]).unwrap();
1669         assert!(chunk.len > 0);
1670
1671         unsafe {
1672             *chunk.data = 0xbe;
1673             assert!(*chunk.data == 0xbe);
1674         }
1675         drop(chunk);
1676
1677         unlink(&path).unwrap();
1678     }
1679
1680     #[test]
1681     #[cfg(windows)]
1682     fn split_paths_windows() {
1683         fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
1684             split_paths(unparsed) ==
1685                 parsed.iter().map(|s| Path::new(*s)).collect::<Vec<_>>()
1686         }
1687
1688         assert!(check_parse("", &mut [""]));
1689         assert!(check_parse(r#""""#, &mut [""]));
1690         assert!(check_parse(";;", &mut ["", "", ""]));
1691         assert!(check_parse(r"c:\", &mut [r"c:\"]));
1692         assert!(check_parse(r"c:\;", &mut [r"c:\", ""]));
1693         assert!(check_parse(r"c:\;c:\Program Files\",
1694                             &mut [r"c:\", r"c:\Program Files\"]));
1695         assert!(check_parse(r#"c:\;c:\"foo"\"#, &mut [r"c:\", r"c:\foo\"]));
1696         assert!(check_parse(r#"c:\;c:\"foo;bar"\;c:\baz"#,
1697                             &mut [r"c:\", r"c:\foo;bar\", r"c:\baz"]));
1698     }
1699
1700     #[test]
1701     #[cfg(unix)]
1702     fn split_paths_unix() {
1703         fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
1704             split_paths(unparsed) ==
1705                 parsed.iter().map(|s| Path::new(*s)).collect::<Vec<_>>()
1706         }
1707
1708         assert!(check_parse("", &mut [""]));
1709         assert!(check_parse("::", &mut ["", "", ""]));
1710         assert!(check_parse("/", &mut ["/"]));
1711         assert!(check_parse("/:", &mut ["/", ""]));
1712         assert!(check_parse("/:/usr/local", &mut ["/", "/usr/local"]));
1713     }
1714
1715     #[test]
1716     #[cfg(unix)]
1717     fn join_paths_unix() {
1718         fn test_eq(input: &[&str], output: &str) -> bool {
1719             join_paths(input).unwrap() == output.as_bytes()
1720         }
1721
1722         assert!(test_eq(&[], ""));
1723         assert!(test_eq(&["/bin", "/usr/bin", "/usr/local/bin"],
1724                          "/bin:/usr/bin:/usr/local/bin"));
1725         assert!(test_eq(&["", "/bin", "", "", "/usr/bin", ""],
1726                          ":/bin:::/usr/bin:"));
1727         assert!(join_paths(&["/te:st"]).is_err());
1728     }
1729
1730     #[test]
1731     #[cfg(windows)]
1732     fn join_paths_windows() {
1733         fn test_eq(input: &[&str], output: &str) -> bool {
1734             join_paths(input).unwrap() == output.as_bytes()
1735         }
1736
1737         assert!(test_eq(&[], ""));
1738         assert!(test_eq(&[r"c:\windows", r"c:\"],
1739                         r"c:\windows;c:\"));
1740         assert!(test_eq(&["", r"c:\windows", "", "", r"c:\", ""],
1741                         r";c:\windows;;;c:\;"));
1742         assert!(test_eq(&[r"c:\te;st", r"c:\"],
1743                         r#""c:\te;st";c:\"#));
1744         assert!(join_paths(&[r#"c:\te"st"#]).is_err());
1745     }
1746
1747     // More recursive_mkdir tests are in extra::tempfile
1748 }