]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/windows/args.rs
Rollup merge of #65144 - clarfon:moo, r=sfackler
[rust.git] / src / libstd / sys / windows / args.rs
1 #![allow(dead_code)] // runtime init functions not used during testing
2
3 use crate::os::windows::prelude::*;
4 use crate::sys::windows::os::current_exe;
5 use crate::sys::c;
6 use crate::ffi::OsString;
7 use crate::fmt;
8 use crate::vec;
9 use crate::slice;
10 use crate::path::PathBuf;
11
12 use core::iter;
13
14 pub unsafe fn init(_argc: isize, _argv: *const *const u8) { }
15
16 pub unsafe fn cleanup() { }
17
18 pub fn args() -> Args {
19     unsafe {
20         let lp_cmd_line = c::GetCommandLineW();
21         let parsed_args_list = parse_lp_cmd_line(
22             lp_cmd_line as *const u16,
23             || current_exe().map(PathBuf::into_os_string).unwrap_or_else(|_| OsString::new()));
24
25         Args { parsed_args_list: parsed_args_list.into_iter() }
26     }
27 }
28
29 /// Implements the Windows command-line argument parsing algorithm.
30 ///
31 /// Microsoft's documentation for the Windows CLI argument format can be found at
32 /// <https://docs.microsoft.com/en-us/previous-versions//17w5ykft(v=vs.85)>.
33 ///
34 /// Windows includes a function to do this in shell32.dll,
35 /// but linking with that DLL causes the process to be registered as a GUI application.
36 /// GUI applications add a bunch of overhead, even if no windows are drawn. See
37 /// <https://randomascii.wordpress.com/2018/12/03/a-not-called-function-can-cause-a-5x-slowdown/>.
38 ///
39 /// This function was tested for equivalence to the shell32.dll implementation in
40 /// Windows 10 Pro v1803, using an exhaustive test suite available at
41 /// <https://gist.github.com/notriddle/dde431930c392e428055b2dc22e638f5> or
42 /// <https://paste.gg/p/anonymous/47d6ed5f5bd549168b1c69c799825223>.
43 unsafe fn parse_lp_cmd_line<F: Fn() -> OsString>(lp_cmd_line: *const u16, exe_name: F)
44                                                  -> Vec<OsString> {
45     const BACKSLASH: u16 = '\\' as u16;
46     const QUOTE: u16 = '"' as u16;
47     const TAB: u16 = '\t' as u16;
48     const SPACE: u16 = ' ' as u16;
49     let mut ret_val = Vec::new();
50     if lp_cmd_line.is_null() || *lp_cmd_line == 0 {
51         ret_val.push(exe_name());
52         return ret_val;
53     }
54     let mut cmd_line = {
55         let mut end = 0;
56         while *lp_cmd_line.offset(end) != 0 {
57             end += 1;
58         }
59         slice::from_raw_parts(lp_cmd_line, end as usize)
60     };
61     // The executable name at the beginning is special.
62     cmd_line = match cmd_line[0] {
63         // The executable name ends at the next quote mark,
64         // no matter what.
65         QUOTE => {
66             let args = {
67                 let mut cut = cmd_line[1..].splitn(2, |&c| c == QUOTE);
68                 if let Some(exe) = cut.next() {
69                     ret_val.push(OsString::from_wide(exe));
70                 }
71                 cut.next()
72             };
73             if let Some(args) = args {
74                 args
75             } else {
76                 return ret_val;
77             }
78         }
79         // Implement quirk: when they say whitespace here,
80         // they include the entire ASCII control plane:
81         // "However, if lpCmdLine starts with any amount of whitespace, CommandLineToArgvW
82         // will consider the first argument to be an empty string. Excess whitespace at the
83         // end of lpCmdLine is ignored."
84         0..=SPACE => {
85             ret_val.push(OsString::new());
86             &cmd_line[1..]
87         },
88         // The executable name ends at the next whitespace,
89         // no matter what.
90         _ => {
91             let args = {
92                 let mut cut = cmd_line.splitn(2, |&c| c > 0 && c <= SPACE);
93                 if let Some(exe) = cut.next() {
94                     ret_val.push(OsString::from_wide(exe));
95                 }
96                 cut.next()
97             };
98             if let Some(args) = args {
99                 args
100             } else {
101                 return ret_val;
102             }
103         }
104     };
105     let mut cur = Vec::new();
106     let mut in_quotes = false;
107     let mut was_in_quotes = false;
108     let mut backslash_count: usize = 0;
109     for &c in cmd_line {
110         match c {
111             // backslash
112             BACKSLASH => {
113                 backslash_count += 1;
114                 was_in_quotes = false;
115             },
116             QUOTE if backslash_count % 2 == 0 => {
117                 cur.extend(iter::repeat(b'\\' as u16).take(backslash_count / 2));
118                 backslash_count = 0;
119                 if was_in_quotes {
120                     cur.push('"' as u16);
121                     was_in_quotes = false;
122                 } else {
123                     was_in_quotes = in_quotes;
124                     in_quotes = !in_quotes;
125                 }
126             }
127             QUOTE if backslash_count % 2 != 0 => {
128                 cur.extend(iter::repeat(b'\\' as u16).take(backslash_count / 2));
129                 backslash_count = 0;
130                 was_in_quotes = false;
131                 cur.push(b'"' as u16);
132             }
133             SPACE | TAB if !in_quotes => {
134                 cur.extend(iter::repeat(b'\\' as u16).take(backslash_count));
135                 if !cur.is_empty() || was_in_quotes {
136                     ret_val.push(OsString::from_wide(&cur[..]));
137                     cur.truncate(0);
138                 }
139                 backslash_count = 0;
140                 was_in_quotes = false;
141             }
142             _ => {
143                 cur.extend(iter::repeat(b'\\' as u16).take(backslash_count));
144                 backslash_count = 0;
145                 was_in_quotes = false;
146                 cur.push(c);
147             }
148         }
149     }
150     cur.extend(iter::repeat(b'\\' as u16).take(backslash_count));
151     // include empty quoted strings at the end of the arguments list
152     if !cur.is_empty() || was_in_quotes || in_quotes {
153         ret_val.push(OsString::from_wide(&cur[..]));
154     }
155     ret_val
156 }
157
158 pub struct Args {
159     parsed_args_list: vec::IntoIter<OsString>,
160 }
161
162 pub struct ArgsInnerDebug<'a> {
163     args: &'a Args,
164 }
165
166 impl<'a> fmt::Debug for ArgsInnerDebug<'a> {
167     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168         self.args.parsed_args_list.as_slice().fmt(f)
169     }
170 }
171
172 impl Args {
173     pub fn inner_debug(&self) -> ArgsInnerDebug<'_> {
174         ArgsInnerDebug {
175             args: self
176         }
177     }
178 }
179
180 impl Iterator for Args {
181     type Item = OsString;
182     fn next(&mut self) -> Option<OsString> { self.parsed_args_list.next() }
183     fn size_hint(&self) -> (usize, Option<usize>) { self.parsed_args_list.size_hint() }
184 }
185
186 impl DoubleEndedIterator for Args {
187     fn next_back(&mut self) -> Option<OsString> { self.parsed_args_list.next_back() }
188 }
189
190 impl ExactSizeIterator for Args {
191     fn len(&self) -> usize { self.parsed_args_list.len() }
192 }
193
194 #[cfg(test)]
195 mod tests {
196     use crate::sys::windows::args::*;
197     use crate::ffi::OsString;
198
199     fn chk(string: &str, parts: &[&str]) {
200         let mut wide: Vec<u16> = OsString::from(string).encode_wide().collect();
201         wide.push(0);
202         let parsed = unsafe {
203             parse_lp_cmd_line(wide.as_ptr() as *const u16, || OsString::from("TEST.EXE"))
204         };
205         let expected: Vec<OsString> = parts.iter().map(|k| OsString::from(k)).collect();
206         assert_eq!(parsed.as_slice(), expected.as_slice());
207     }
208
209     #[test]
210     fn empty() {
211         chk("", &["TEST.EXE"]);
212         chk("\0", &["TEST.EXE"]);
213     }
214
215     #[test]
216     fn single_words() {
217         chk("EXE one_word", &["EXE", "one_word"]);
218         chk("EXE a", &["EXE", "a"]);
219         chk("EXE ðŸ˜…", &["EXE", "😅"]);
220         chk("EXE ðŸ˜…🤦", &["EXE", "😅🤦"]);
221     }
222
223     #[test]
224     fn official_examples() {
225         chk(r#"EXE "abc" d e"#, &["EXE", "abc", "d", "e"]);
226         chk(r#"EXE a\\\b d"e f"g h"#, &["EXE", r#"a\\\b"#, "de fg", "h"]);
227         chk(r#"EXE a\\\"b c d"#, &["EXE", r#"a\"b"#, "c", "d"]);
228         chk(r#"EXE a\\\\"b c" d e"#, &["EXE", r#"a\\b c"#, "d", "e"]);
229     }
230
231     #[test]
232     fn whitespace_behavior() {
233         chk(r#" test"#, &["", "test"]);
234         chk(r#"  test"#, &["", "test"]);
235         chk(r#" test test2"#, &["", "test", "test2"]);
236         chk(r#" test  test2"#, &["", "test", "test2"]);
237         chk(r#"test test2 "#, &["test", "test2"]);
238         chk(r#"test  test2 "#, &["test", "test2"]);
239         chk(r#"test "#, &["test"]);
240     }
241
242     #[test]
243     fn genius_quotes() {
244         chk(r#"EXE "" """#, &["EXE", "", ""]);
245         chk(r#"EXE "" """"#, &["EXE", "", "\""]);
246         chk(
247             r#"EXE "this is """all""" in the same argument""#,
248             &["EXE", "this is \"all\" in the same argument"]
249         );
250         chk(r#"EXE "a"""#, &["EXE", "a\""]);
251         chk(r#"EXE "a"" a"#, &["EXE", "a\"", "a"]);
252         // quotes cannot be escaped in command names
253         chk(r#""EXE" check"#, &["EXE", "check"]);
254         chk(r#""EXE check""#, &["EXE check"]);
255         chk(r#""EXE """for""" check"#, &["EXE ", r#"for""#, "check"]);
256         chk(r#""EXE \"for\" check"#, &[r#"EXE \"#, r#"for""#,  "check"]);
257     }
258 }