1 //! Global initialization and retrieval of command line arguments.
3 //! On some platforms these are stored during runtime startup,
4 //! and on some they are retrieved from the system on demand.
6 #![allow(dead_code)] // runtime init functions not used during testing
8 use crate::ffi::OsString;
12 /// One-time global initialization.
13 pub unsafe fn init(argc: isize, argv: *const *const u8) {
17 /// Returns the command line arguments
18 pub fn args() -> Args {
23 iter: vec::IntoIter<OsString>,
26 impl !Send for Args {}
27 impl !Sync for Args {}
29 impl fmt::Debug for Args {
30 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31 self.iter.as_slice().fmt(f)
35 impl Iterator for Args {
37 fn next(&mut self) -> Option<OsString> {
40 fn size_hint(&self) -> (usize, Option<usize>) {
45 impl ExactSizeIterator for Args {
46 fn len(&self) -> usize {
51 impl DoubleEndedIterator for Args {
52 fn next_back(&mut self) -> Option<OsString> {
59 target_os = "android",
60 target_os = "freebsd",
61 target_os = "dragonfly",
63 target_os = "openbsd",
64 target_os = "solaris",
65 target_os = "illumos",
66 target_os = "emscripten",
69 target_os = "fuchsia",
75 use crate::ffi::{CStr, OsString};
76 use crate::os::unix::prelude::*;
78 use crate::sync::atomic::{AtomicIsize, AtomicPtr, Ordering};
80 // The system-provided argc and argv, which we store in static memory
81 // here so that we can defer the work of parsing them until its actually
84 // Note that we never mutate argv/argc, the argv array, or the argv
85 // strings, which allows the code in this file to be very simple.
86 static ARGC: AtomicIsize = AtomicIsize::new(0);
87 static ARGV: AtomicPtr<*const u8> = AtomicPtr::new(ptr::null_mut());
89 unsafe fn really_init(argc: isize, argv: *const *const u8) {
90 // These don't need to be ordered with each other or other stores,
91 // because they only hold the unmodified system-provide argv/argc.
92 ARGC.store(argc, Ordering::Relaxed);
93 ARGV.store(argv as *mut _, Ordering::Relaxed);
97 pub unsafe fn init(_argc: isize, _argv: *const *const u8) {
98 // On Linux-GNU, we rely on `ARGV_INIT_ARRAY` below to initialize
99 // `ARGC` and `ARGV`. But in Miri that does not actually happen so we
100 // still initialize here.
101 #[cfg(any(miri, not(all(target_os = "linux", target_env = "gnu"))))]
102 really_init(_argc, _argv);
105 /// glibc passes argc, argv, and envp to functions in .init_array, as a non-standard extension.
106 /// This allows `std::env::args` to work even in a `cdylib`, as it does on macOS and Windows.
107 #[cfg(all(target_os = "linux", target_env = "gnu"))]
109 #[link_section = ".init_array.00099"]
110 static ARGV_INIT_ARRAY: extern "C" fn(
111 crate::os::raw::c_int,
115 extern "C" fn init_wrapper(
116 argc: crate::os::raw::c_int,
117 argv: *const *const u8,
118 _envp: *const *const u8,
121 really_init(argc as isize, argv);
127 pub fn args() -> Args {
128 Args { iter: clone().into_iter() }
131 fn clone() -> Vec<OsString> {
133 // Load ARGC and ARGV, which hold the unmodified system-provided
134 // argc/argv, so we can read the pointed-to memory without atomics
135 // or synchronization.
137 // If either ARGC or ARGV is still zero or null, then either there
138 // really are no arguments, or someone is asking for `args()`
139 // before initialization has completed, and we return an empty
141 let argv = ARGV.load(Ordering::Relaxed);
142 let argc = if argv.is_null() { 0 } else { ARGC.load(Ordering::Relaxed) };
145 let cstr = CStr::from_ptr(*argv.offset(i) as *const libc::c_char);
146 OsStringExt::from_vec(cstr.to_bytes().to_vec())
153 #[cfg(any(target_os = "macos", target_os = "ios"))]
156 use crate::ffi::CStr;
158 pub unsafe fn init(_argc: isize, _argv: *const *const u8) {}
160 #[cfg(target_os = "macos")]
161 pub fn args() -> Args {
162 use crate::os::unix::prelude::*;
164 // These functions are in crt_externs.h.
165 fn _NSGetArgc() -> *mut libc::c_int;
166 fn _NSGetArgv() -> *mut *mut *mut libc::c_char;
171 (*_NSGetArgc() as isize, *_NSGetArgv() as *const *const libc::c_char);
174 let bytes = CStr::from_ptr(*argv.offset(i)).to_bytes().to_vec();
175 OsStringExt::from_vec(bytes)
179 Args { iter: vec.into_iter() }
182 // As _NSGetArgc and _NSGetArgv aren't mentioned in iOS docs
183 // and use underscores in their names - they're most probably
184 // are considered private and therefore should be avoided
185 // Here is another way to get arguments using Objective C
188 // In general it looks like:
190 // let args = [[NSProcessInfo processInfo] arguments]
191 // for i in (0..[args count])
192 // res.push([args objectAtIndex:i])
194 #[cfg(target_os = "ios")]
195 pub fn args() -> Args {
196 use crate::ffi::OsString;
201 fn sel_registerName(name: *const libc::c_uchar) -> Sel;
202 fn objc_getClass(class_name: *const libc::c_uchar) -> NsId;
205 #[cfg(target_arch = "aarch64")]
207 fn objc_msgSend(obj: NsId, sel: Sel) -> NsId;
208 #[allow(clashing_extern_declarations)]
209 #[link_name = "objc_msgSend"]
210 fn objc_msgSend_ul(obj: NsId, sel: Sel, i: libc::c_ulong) -> NsId;
213 #[cfg(not(target_arch = "aarch64"))]
215 fn objc_msgSend(obj: NsId, sel: Sel, ...) -> NsId;
216 #[allow(clashing_extern_declarations)]
217 #[link_name = "objc_msgSend"]
218 fn objc_msgSend_ul(obj: NsId, sel: Sel, ...) -> NsId;
221 type Sel = *const libc::c_void;
222 type NsId = *const libc::c_void;
224 let mut res = Vec::new();
227 let process_info_sel = sel_registerName("processInfo\0".as_ptr());
228 let arguments_sel = sel_registerName("arguments\0".as_ptr());
229 let utf8_sel = sel_registerName("UTF8String\0".as_ptr());
230 let count_sel = sel_registerName("count\0".as_ptr());
231 let object_at_sel = sel_registerName("objectAtIndex:\0".as_ptr());
233 let klass = objc_getClass("NSProcessInfo\0".as_ptr());
234 let info = objc_msgSend(klass, process_info_sel);
235 let args = objc_msgSend(info, arguments_sel);
237 let cnt: usize = mem::transmute(objc_msgSend(args, count_sel));
239 let tmp = objc_msgSend_ul(args, object_at_sel, i as libc::c_ulong);
240 let utf_c_str: *const libc::c_char = mem::transmute(objc_msgSend(tmp, utf8_sel));
241 let bytes = CStr::from_ptr(utf_c_str).to_bytes();
242 res.push(OsString::from(str::from_utf8(bytes).unwrap()))
246 Args { iter: res.into_iter() }
250 #[cfg(target_os = "espidf")]
255 pub unsafe fn init(_argc: isize, _argv: *const *const u8) {}
257 pub fn args() -> Args {
258 Args { iter: Vec::new().into_iter() }