Skip to content

Commit 382f9a7

Browse files
committed
wasi: Load arguments via syscalls
This commit switches the wasi target to loading CLI arguments via the syscalls provided by wasi rather than through the argc/argv passed to the main function. While serving the same purpose it's hoped that using syscalls will make us a bit more portable (less reliance from libstd on an external C library) as well as avoiding the need for a lock!
1 parent eab3eb3 commit 382f9a7

File tree

1 file changed

+24
-26
lines changed

1 file changed

+24
-26
lines changed

src/libstd/sys/wasi/args.rs

Lines changed: 24 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,15 @@
1-
use crate::any::Any;
21
use crate::ffi::CStr;
2+
use crate::io;
3+
use crate::sys::cvt_wasi;
34
use crate::ffi::OsString;
45
use crate::marker::PhantomData;
56
use crate::os::wasi::ffi::OsStringExt;
6-
use crate::ptr;
77
use crate::vec;
88

9-
static mut ARGC: isize = 0;
10-
static mut ARGV: *const *const u8 = ptr::null();
11-
12-
#[cfg(not(target_feature = "atomics"))]
13-
pub unsafe fn args_lock() -> impl Any {
14-
// No need for a lock if we're single-threaded, but this function will need
15-
// to get implemented for multi-threaded scenarios
16-
}
17-
18-
pub unsafe fn init(argc: isize, argv: *const *const u8) {
19-
let _guard = args_lock();
20-
ARGC = argc;
21-
ARGV = argv;
9+
pub unsafe fn init(_argc: isize, _argv: *const *const u8) {
2210
}
2311

2412
pub unsafe fn cleanup() {
25-
let _guard = args_lock();
26-
ARGC = 0;
27-
ARGV = ptr::null();
2813
}
2914

3015
pub struct Args {
@@ -34,18 +19,31 @@ pub struct Args {
3419

3520
/// Returns the command line arguments
3621
pub fn args() -> Args {
22+
maybe_args().unwrap_or_else(|_| {
23+
Args {
24+
iter: Vec::new().into_iter(),
25+
_dont_send_or_sync_me: PhantomData
26+
}
27+
})
28+
}
29+
30+
fn maybe_args() -> io::Result<Args> {
3731
unsafe {
38-
let _guard = args_lock();
39-
let args = (0..ARGC)
40-
.map(|i| {
41-
let cstr = CStr::from_ptr(*ARGV.offset(i) as *const libc::c_char);
42-
OsStringExt::from_vec(cstr.to_bytes().to_vec())
43-
})
32+
let (mut argc, mut argv_buf_size) = (0, 0);
33+
cvt_wasi(libc::__wasi_args_sizes_get(&mut argc, &mut argv_buf_size))?;
34+
35+
let mut argc = vec![0 as *mut libc::c_char; argc];
36+
let mut argv_buf = vec![0; argv_buf_size];
37+
cvt_wasi(libc::__wasi_args_get(argc.as_mut_ptr(), argv_buf.as_mut_ptr()))?;
38+
39+
let args = argc.into_iter()
40+
.map(|ptr| CStr::from_ptr(ptr).to_bytes().to_vec())
41+
.map(|bytes| OsString::from_vec(bytes))
4442
.collect::<Vec<_>>();
45-
Args {
43+
Ok(Args {
4644
iter: args.into_iter(),
4745
_dont_send_or_sync_me: PhantomData,
48-
}
46+
})
4947
}
5048
}
5149

0 commit comments

Comments
 (0)