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