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