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.
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.
11 //! Global initialization and retreival of command line arguments.
13 //! On some platforms these are stored during runtime startup,
14 //! and on some they are retrieved from the system on demand.
16 #![allow(dead_code)] // runtime init functions not used during testing
19 use marker::PhantomData;
22 /// One-time global initialization.
23 pub unsafe fn init(argc: isize, argv: *const *const u8) { imp::init(argc, argv) }
25 /// One-time global cleanup.
26 pub unsafe fn cleanup() { imp::cleanup() }
28 /// Returns the command line arguments
29 pub fn args() -> Args {
34 iter: vec::IntoIter<OsString>,
35 _dont_send_or_sync_me: PhantomData<*mut ()>,
38 impl Iterator for Args {
40 fn next(&mut self) -> Option<OsString> { self.iter.next() }
41 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
44 impl ExactSizeIterator for Args {
45 fn len(&self) -> usize { self.iter.len() }
48 impl DoubleEndedIterator for Args {
49 fn next_back(&mut self) -> Option<OsString> { self.iter.next_back() }
52 #[cfg(any(target_os = "linux",
53 target_os = "android",
54 target_os = "freebsd",
55 target_os = "dragonfly",
58 target_os = "openbsd",
59 target_os = "solaris",
60 target_os = "emscripten",
62 target_os = "fuchsia"))]
64 use os::unix::prelude::*;
66 use ffi::{CStr, OsString};
67 use marker::PhantomData;
71 use sys_common::mutex::Mutex;
73 static mut GLOBAL_ARGS_PTR: usize = 0;
74 static LOCK: Mutex = Mutex::new();
76 pub unsafe fn init(argc: isize, argv: *const *const u8) {
77 let args = (0..argc).map(|i| {
78 CStr::from_ptr(*argv.offset(i) as *const libc::c_char).to_bytes().to_vec()
82 let ptr = get_global_ptr();
83 assert!((*ptr).is_none());
84 (*ptr) = Some(box args);
88 pub unsafe fn cleanup() {
90 *get_global_ptr() = None;
94 pub fn args() -> Args {
95 let bytes = clone().unwrap_or(Vec::new());
96 let v: Vec<OsString> = bytes.into_iter().map(|v| {
97 OsStringExt::from_vec(v)
99 Args { iter: v.into_iter(), _dont_send_or_sync_me: PhantomData }
102 fn clone() -> Option<Vec<Vec<u8>>> {
105 let ptr = get_global_ptr();
106 let ret = (*ptr).as_ref().map(|s| (**s).clone());
112 fn get_global_ptr() -> *mut Option<Box<Vec<Vec<u8>>>> {
113 unsafe { mem::transmute(&GLOBAL_ARGS_PTR) }
118 #[cfg(any(target_os = "macos",
122 use marker::PhantomData;
126 pub unsafe fn init(_argc: isize, _argv: *const *const u8) {
132 #[cfg(target_os = "macos")]
133 pub fn args() -> Args {
134 use os::unix::prelude::*;
136 // These functions are in crt_externs.h.
137 fn _NSGetArgc() -> *mut libc::c_int;
138 fn _NSGetArgv() -> *mut *mut *mut libc::c_char;
142 let (argc, argv) = (*_NSGetArgc() as isize,
143 *_NSGetArgv() as *const *const libc::c_char);
144 (0.. argc as isize).map(|i| {
145 let bytes = CStr::from_ptr(*argv.offset(i)).to_bytes().to_vec();
146 OsStringExt::from_vec(bytes)
147 }).collect::<Vec<_>>()
150 iter: vec.into_iter(),
151 _dont_send_or_sync_me: PhantomData,
155 // As _NSGetArgc and _NSGetArgv aren't mentioned in iOS docs
156 // and use underscores in their names - they're most probably
157 // are considered private and therefore should be avoided
158 // Here is another way to get arguments using Objective C
161 // In general it looks like:
163 // let args = [[NSProcessInfo processInfo] arguments]
164 // for i in (0..[args count])
165 // res.push([args objectAtIndex:i])
167 #[cfg(target_os = "ios")]
168 pub fn args() -> Args {
174 fn sel_registerName(name: *const libc::c_uchar) -> Sel;
175 fn objc_getClass(class_name: *const libc::c_uchar) -> NsId;
178 #[cfg(target_arch="aarch64")]
180 fn objc_msgSend(obj: NsId, sel: Sel) -> NsId;
181 #[link_name="objc_msgSend"]
182 fn objc_msgSend_ul(obj: NsId, sel: Sel, i: libc::c_ulong) -> NsId;
185 #[cfg(not(target_arch="aarch64"))]
187 fn objc_msgSend(obj: NsId, sel: Sel, ...) -> NsId;
188 #[link_name="objc_msgSend"]
189 fn objc_msgSend_ul(obj: NsId, sel: Sel, ...) -> NsId;
192 #[link(name = "Foundation", kind = "framework")]
193 #[link(name = "objc")]
194 #[cfg(not(cargobuild))]
197 type Sel = *const libc::c_void;
198 type NsId = *const libc::c_void;
200 let mut res = Vec::new();
203 let process_info_sel = sel_registerName("processInfo\0".as_ptr());
204 let arguments_sel = sel_registerName("arguments\0".as_ptr());
205 let utf8_sel = sel_registerName("UTF8String\0".as_ptr());
206 let count_sel = sel_registerName("count\0".as_ptr());
207 let object_at_sel = sel_registerName("objectAtIndex:\0".as_ptr());
209 let klass = objc_getClass("NSProcessInfo\0".as_ptr());
210 let info = objc_msgSend(klass, process_info_sel);
211 let args = objc_msgSend(info, arguments_sel);
213 let cnt: usize = mem::transmute(objc_msgSend(args, count_sel));
215 let tmp = objc_msgSend_ul(args, object_at_sel, i as libc::c_ulong);
216 let utf_c_str: *const libc::c_char =
217 mem::transmute(objc_msgSend(tmp, utf8_sel));
218 let bytes = CStr::from_ptr(utf_c_str).to_bytes();
219 res.push(OsString::from(str::from_utf8(bytes).unwrap()))
223 Args { iter: res.into_iter(), _dont_send_or_sync_me: PhantomData }