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