std/sys/args/
unix.rs

1//! Global initialization and retrieval of command line arguments.
2//!
3//! On some platforms these are stored during runtime startup,
4//! and on some they are retrieved from the system on demand.
5
6#![allow(dead_code)] // runtime init functions not used during testing
7
8use crate::ffi::CStr;
9use crate::os::unix::ffi::OsStringExt;
10
11#[path = "common.rs"]
12mod common;
13pub use common::Args;
14
15/// One-time global initialization.
16pub unsafe fn init(argc: isize, argv: *const *const u8) {
17    unsafe { imp::init(argc, argv) }
18}
19
20/// Returns the command line arguments
21pub fn args() -> Args {
22    let (argc, argv) = imp::argc_argv();
23
24    let mut vec = Vec::with_capacity(argc as usize);
25
26    for i in 0..argc {
27        // SAFETY: `argv` is non-null if `argc` is positive, and it is
28        // guaranteed to be at least as long as `argc`, so reading from it
29        // should be safe.
30        let ptr = unsafe { argv.offset(i).read() };
31
32        // Some C commandline parsers (e.g. GLib and Qt) are replacing already
33        // handled arguments in `argv` with `NULL` and move them to the end.
34        //
35        // Since they can't directly ensure updates to `argc` as well, this
36        // means that `argc` might be bigger than the actual number of
37        // non-`NULL` pointers in `argv` at this point.
38        //
39        // To handle this we simply stop iterating at the first `NULL`
40        // argument. `argv` is also guaranteed to be `NULL`-terminated so any
41        // non-`NULL` arguments after the first `NULL` can safely be ignored.
42        if ptr.is_null() {
43            // NOTE: On Apple platforms, `-[NSProcessInfo arguments]` does not
44            // stop iterating here, but instead `continue`, always iterating
45            // up until it reached `argc`.
46            //
47            // This difference will only matter in very specific circumstances
48            // where `argc`/`argv` have been modified, but in unexpected ways,
49            // so it likely doesn't really matter which option we choose.
50            // See the following PR for further discussion:
51            // <https://github.com/rust-lang/rust/pull/125225>
52            break;
53        }
54
55        // SAFETY: Just checked that the pointer is not NULL, and arguments
56        // are otherwise guaranteed to be valid C strings.
57        let cstr = unsafe { CStr::from_ptr(ptr) };
58        vec.push(OsStringExt::from_vec(cstr.to_bytes().to_vec()));
59    }
60
61    Args::new(vec)
62}
63
64#[cfg(any(
65    target_os = "linux",
66    target_os = "android",
67    target_os = "freebsd",
68    target_os = "dragonfly",
69    target_os = "netbsd",
70    target_os = "openbsd",
71    target_os = "cygwin",
72    target_os = "solaris",
73    target_os = "illumos",
74    target_os = "emscripten",
75    target_os = "haiku",
76    target_os = "l4re",
77    target_os = "fuchsia",
78    target_os = "redox",
79    target_os = "vxworks",
80    target_os = "horizon",
81    target_os = "aix",
82    target_os = "nto",
83    target_os = "hurd",
84    target_os = "rtems",
85    target_os = "nuttx",
86))]
87mod imp {
88    use crate::ffi::c_char;
89    use crate::ptr;
90    use crate::sync::atomic::{AtomicIsize, AtomicPtr, Ordering};
91
92    // The system-provided argc and argv, which we store in static memory
93    // here so that we can defer the work of parsing them until its actually
94    // needed.
95    //
96    // Note that we never mutate argv/argc, the argv array, or the argv
97    // strings, which allows the code in this file to be very simple.
98    static ARGC: AtomicIsize = AtomicIsize::new(0);
99    static ARGV: AtomicPtr<*const u8> = AtomicPtr::new(ptr::null_mut());
100
101    unsafe fn really_init(argc: isize, argv: *const *const u8) {
102        // These don't need to be ordered with each other or other stores,
103        // because they only hold the unmodified system-provide argv/argc.
104        ARGC.store(argc, Ordering::Relaxed);
105        ARGV.store(argv as *mut _, Ordering::Relaxed);
106    }
107
108    #[inline(always)]
109    pub unsafe fn init(argc: isize, argv: *const *const u8) {
110        // on GNU/Linux if we are main then we will init argv and argc twice, it "duplicates work"
111        // BUT edge-cases are real: only using .init_array can break most emulators, dlopen, etc.
112        unsafe { really_init(argc, argv) };
113    }
114
115    /// glibc passes argc, argv, and envp to functions in .init_array, as a non-standard extension.
116    /// This allows `std::env::args` to work even in a `cdylib`, as it does on macOS and Windows.
117    #[cfg(all(target_os = "linux", target_env = "gnu"))]
118    #[used]
119    #[unsafe(link_section = ".init_array.00099")]
120    static ARGV_INIT_ARRAY: extern "C" fn(
121        crate::os::raw::c_int,
122        *const *const u8,
123        *const *const u8,
124    ) = {
125        extern "C" fn init_wrapper(
126            argc: crate::os::raw::c_int,
127            argv: *const *const u8,
128            _envp: *const *const u8,
129        ) {
130            unsafe { really_init(argc as isize, argv) };
131        }
132        init_wrapper
133    };
134
135    pub fn argc_argv() -> (isize, *const *const c_char) {
136        // Load ARGC and ARGV, which hold the unmodified system-provided
137        // argc/argv, so we can read the pointed-to memory without atomics or
138        // synchronization.
139        //
140        // If either ARGC or ARGV is still zero or null, then either there
141        // really are no arguments, or someone is asking for `args()` before
142        // initialization has completed, and we return an empty list.
143        let argv = ARGV.load(Ordering::Relaxed);
144        let argc = if argv.is_null() { 0 } else { ARGC.load(Ordering::Relaxed) };
145
146        // Cast from `*mut *const u8` to `*const *const c_char`
147        (argc, argv.cast())
148    }
149}
150
151// Use `_NSGetArgc` and `_NSGetArgv` on Apple platforms.
152//
153// Even though these have underscores in their names, they've been available
154// since the first versions of both macOS and iOS, and are declared in
155// the header `crt_externs.h`.
156//
157// NOTE: This header was added to the iOS 13.0 SDK, which has been the source
158// of a great deal of confusion in the past about the availability of these
159// APIs.
160//
161// NOTE(madsmtm): This has not strictly been verified to not cause App Store
162// rejections; if this is found to be the case, the previous implementation
163// of this used `[[NSProcessInfo processInfo] arguments]`.
164#[cfg(target_vendor = "apple")]
165mod imp {
166    use crate::ffi::{c_char, c_int};
167
168    pub unsafe fn init(_argc: isize, _argv: *const *const u8) {
169        // No need to initialize anything in here, `libdyld.dylib` has already
170        // done the work for us.
171    }
172
173    pub fn argc_argv() -> (isize, *const *const c_char) {
174        unsafe extern "C" {
175            // These functions are in crt_externs.h.
176            fn _NSGetArgc() -> *mut c_int;
177            fn _NSGetArgv() -> *mut *mut *mut c_char;
178        }
179
180        // SAFETY: The returned pointer points to a static initialized early
181        // in the program lifetime by `libdyld.dylib`, and as such is always
182        // valid.
183        //
184        // NOTE: Similar to `_NSGetEnviron`, there technically isn't anything
185        // protecting us against concurrent modifications to this, and there
186        // doesn't exist a lock that we can take. Instead, it is generally
187        // expected that it's only modified in `main` / before other code
188        // runs, so reading this here should be fine.
189        let argc = unsafe { _NSGetArgc().read() };
190        // SAFETY: Same as above.
191        let argv = unsafe { _NSGetArgv().read() };
192
193        // Cast from `*mut *mut c_char` to `*const *const c_char`
194        (argc as isize, argv.cast())
195    }
196}