1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
use vec::Vec;
pub unsafe fn init(argc: isize, argv: *const *const u8) { imp::init(argc, argv) }
pub unsafe fn cleanup() { imp::cleanup() }
pub fn take() -> Option<Vec<Vec<u8>>> { imp::take() }
pub fn put(args: Vec<Vec<u8>>) { imp::put(args) }
pub fn clone() -> Option<Vec<Vec<u8>>> { imp::clone() }
#[cfg(any(target_os = "linux",
target_os = "android",
target_os = "freebsd",
target_os = "dragonfly",
target_os = "bitrig",
target_os = "netbsd",
target_os = "openbsd"))]
mod imp {
use prelude::v1::*;
use libc;
use mem;
use ffi::CStr;
use sync::StaticMutex;
static mut GLOBAL_ARGS_PTR: usize = 0;
static LOCK: StaticMutex = StaticMutex::new();
pub unsafe fn init(argc: isize, argv: *const *const u8) {
let args = load_argc_and_argv(argc, argv);
put(args);
}
pub unsafe fn cleanup() {
take();
LOCK.destroy();
}
pub fn take() -> Option<Vec<Vec<u8>>> {
let _guard = LOCK.lock();
unsafe {
let ptr = get_global_ptr();
let val = mem::replace(&mut *ptr, None);
val.as_ref().map(|s: &Box<Vec<Vec<u8>>>| (**s).clone())
}
}
pub fn put(args: Vec<Vec<u8>>) {
let _guard = LOCK.lock();
unsafe {
let ptr = get_global_ptr();
rtassert!((*ptr).is_none());
(*ptr) = Some(box args.clone());
}
}
pub fn clone() -> Option<Vec<Vec<u8>>> {
let _guard = LOCK.lock();
unsafe {
let ptr = get_global_ptr();
(*ptr).as_ref().map(|s: &Box<Vec<Vec<u8>>>| (**s).clone())
}
}
fn get_global_ptr() -> *mut Option<Box<Vec<Vec<u8>>>> {
unsafe { mem::transmute(&GLOBAL_ARGS_PTR) }
}
unsafe fn load_argc_and_argv(argc: isize,
argv: *const *const u8) -> Vec<Vec<u8>> {
let argv = argv as *const *const libc::c_char;
(0..argc).map(|i| {
CStr::from_ptr(*argv.offset(i)).to_bytes().to_vec()
}).collect()
}
#[cfg(test)]
mod tests {
use prelude::v1::*;
use super::*;
#[test]
fn smoke_test() {
let saved_value = take();
let expected = vec![
b"happy".to_vec(),
b"today?".to_vec(),
];
put(expected.clone());
assert!(clone() == Some(expected.clone()));
assert!(take() == Some(expected.clone()));
assert!(take() == None);
match saved_value {
Some(ref args) => put(args.clone()),
None => ()
}
}
}
}
#[cfg(any(target_os = "macos",
target_os = "ios",
target_os = "windows"))]
mod imp {
use vec::Vec;
pub unsafe fn init(_argc: isize, _argv: *const *const u8) {
}
pub fn cleanup() {
}
pub fn take() -> Option<Vec<Vec<u8>>> {
panic!()
}
pub fn put(_args: Vec<Vec<u8>>) {
panic!()
}
pub fn clone() -> Option<Vec<Vec<u8>>> {
panic!()
}
}