Skip to content

Commit eb54ddd

Browse files
Rollup merge of #87279 - sunfishcode:document-unix-argv, r=RalfJung
Add comments explaining the unix command-line argument support. Following up on #87236, add comments to the unix command-line argument support explaining that the code doesn't mutate the system-provided argc/argv, and that this is why the code doesn't need a lock or special memory ordering. r? ```@RalfJung```
2 parents 1008ace + 2a56a68 commit eb54ddd

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

library/std/src/sys/unix/args.rs

+16-2
Original file line numberDiff line numberDiff line change
@@ -77,10 +77,18 @@ mod imp {
7777
use crate::ptr;
7878
use crate::sync::atomic::{AtomicIsize, AtomicPtr, Ordering};
7979

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
82+
// needed.
83+
//
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.
8086
static ARGC: AtomicIsize = AtomicIsize::new(0);
8187
static ARGV: AtomicPtr<*const u8> = AtomicPtr::new(ptr::null_mut());
8288

8389
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.
8492
ARGC.store(argc, Ordering::Relaxed);
8593
ARGV.store(argv as *mut _, Ordering::Relaxed);
8694
}
@@ -122,8 +130,14 @@ mod imp {
122130

123131
fn clone() -> Vec<OsString> {
124132
unsafe {
125-
// Load ARGC and ARGV without a lock. If the store to either ARGV or
126-
// ARGC isn't visible yet, we'll return an empty argument list.
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.
136+
//
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
140+
// list.
127141
let argv = ARGV.load(Ordering::Relaxed);
128142
let argc = if argv.is_null() { 0 } else { ARGC.load(Ordering::Relaxed) };
129143
(0..argc)

0 commit comments

Comments
 (0)