1use std::{
45 collections::VecDeque,
46 fmt,
47 io::{Read, Write},
48 path::Path,
49 sync::Once,
50};
51
52use crate::{
53 component::{self, Address, Component},
54 components::Eeprom,
55 error::{Error, Result},
56 sys,
57 value::{OcString, Value},
58};
59
60#[derive(Clone, Debug, PartialEq, Eq)]
62pub enum ExitStatus {
63 Exited(i32),
65 Crashed(String),
67}
68
69impl ExitStatus {
70 pub fn success(&self) -> bool {
71 matches!(self, ExitStatus::Exited(0))
72 }
73
74 pub fn code(&self) -> Option<i32> {
76 match self {
77 ExitStatus::Exited(code) => Some(*code),
78 ExitStatus::Crashed(_) => None,
79 }
80 }
81}
82
83impl fmt::Display for ExitStatus {
84 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85 match self {
86 ExitStatus::Exited(code) => write!(f, "exit status: {code}"),
87 ExitStatus::Crashed(message) => write!(f, "crashed: {message}"),
88 }
89 }
90}
91
92#[derive(Clone, Debug, PartialEq, Eq)]
94pub struct Output {
95 pub status: ExitStatus,
96 pub stdout: Vec<u8>,
98}
99
100#[derive(Clone, Debug, PartialEq, Eq)]
102pub enum Event {
103 Output(Vec<u8>),
105 Input,
109 Exit(ExitStatus),
111}
112
113#[derive(Clone, Debug)]
115pub struct Command {
116 program: String,
117 image: Option<Vec<u8>>,
118 args: Vec<String>,
119 env: Vec<(String, Option<String>)>,
120 env_clear: bool,
121 disk: Option<Address>,
122 cwd: Option<String>,
123}
124
125impl Command {
126 pub fn new(program: impl Into<String>) -> Command {
131 Command {
132 program: program.into(),
133 image: None,
134 args: Vec::new(),
135 env: Vec::new(),
136 env_clear: false,
137 disk: None,
138 cwd: None,
139 }
140 }
141
142 pub fn from_image(name: impl Into<String>, image: impl Into<Vec<u8>>) -> Command {
144 Command { image: Some(image.into()), ..Command::new(name) }
145 }
146
147 pub fn arg(&mut self, arg: impl Into<String>) -> &mut Command {
148 self.args.push(arg.into());
149 self
150 }
151
152 pub fn args<I: IntoIterator<Item = S>, S: Into<String>>(&mut self, args: I) -> &mut Command {
153 self.args.extend(args.into_iter().map(Into::into));
154 self
155 }
156
157 pub fn env(&mut self, key: impl Into<String>, value: impl Into<String>) -> &mut Command {
158 self.env.push((key.into(), Some(value.into())));
159 self
160 }
161
162 pub fn envs<I: IntoIterator<Item = (K, V)>, K: Into<String>, V: Into<String>>(&mut self, vars: I) -> &mut Command {
163 self.env.extend(vars.into_iter().map(|(k, v)| (k.into(), Some(v.into()))));
164 self
165 }
166
167 pub fn env_remove(&mut self, key: impl Into<String>) -> &mut Command {
168 self.env.push((key.into(), None));
169 self
170 }
171
172 pub fn env_clear(&mut self) -> &mut Command {
174 self.env_clear = true;
175 self.env.clear();
176 self
177 }
178
179 pub fn disk(&mut self, disk: impl Into<Address>) -> &mut Command {
181 self.disk = Some(disk.into());
182 self
183 }
184
185 pub fn current_dir(&mut self, dir: impl AsRef<Path>) -> &mut Command {
189 self.cwd = Some(dir.as_ref().to_string_lossy().into_owned());
190 self
191 }
192
193 pub fn get_current_dir(&self) -> Option<&Path> {
194 self.cwd.as_deref().map(Path::new)
195 }
196
197 pub fn get_program(&self) -> &str {
198 &self.program
199 }
200
201 pub fn get_args(&self) -> &[String] {
202 &self.args
203 }
204
205 pub fn spawn(&mut self) -> Result<Child> {
207 let mut base = vec![
208 ("argv", Value::from(std::iter::once(self.program.clone()).chain(self.args.iter().cloned()).collect::<Vec<_>>())),
209 ("env", Value::from(self.environment())),
210 ];
211 if let Some(dir) = self.child_dir() {
212 base.push(("cwd", Value::from(dir)));
213 }
214 if let Some(image) = &self.image {
215 base.push(("image", Value::String(OcString(image.clone()))));
216 return Child::start(&spec(base)).map(|c| c.expect("images are never missing"));
217 }
218 let disks: Vec<Option<Address>> = match &self.disk {
219 Some(disk) => vec![Some(disk.clone())],
220 None => search_disks(),
221 };
222 for disk in disks {
223 for path in self.candidate_paths() {
224 let mut entries = base.clone();
225 entries.push(("path", Value::from(path)));
226 if let Some(disk) = &disk {
227 entries.push(("disk", Value::from(disk)));
228 }
229 if let Some(child) = Child::start(&spec(entries))? {
230 return Ok(child);
231 }
232 }
233 }
234 Err(Error::ProgramNotFound(self.program.clone()))
235 }
236
237 pub fn status(&mut self) -> Result<ExitStatus> {
239 self.spawn()?.wait()
240 }
241
242 pub fn output(&mut self) -> Result<Output> {
245 let mut child = self.spawn()?;
246 child.close_stdin();
247 child.wait_with_output()
248 }
249
250 fn environment(&self) -> Vec<String> {
251 let mut vars: Vec<(String, String)> = if self.env_clear { Vec::new() } else { std::env::vars().collect() };
252 for (key, value) in &self.env {
253 vars.retain(|(k, _)| k != key);
254 if let Some(value) = value {
255 vars.push((key.clone(), value.clone()));
256 }
257 }
258 vars.into_iter().map(|(k, v)| format!("{k}={v}")).collect()
259 }
260
261 fn child_dir(&self) -> Option<String> {
265 let here = std::env::current_dir().ok().map(|dir| dir.to_string_lossy().into_owned());
266 match (&self.cwd, here) {
267 (Some(dir), Some(here)) if !dir.starts_with('/') => Some(format!("{}/{dir}", here.trim_end_matches('/'))),
268 (Some(dir), _) => Some(dir.clone()),
269 (None, here) => here,
270 }
271 }
272
273 fn candidate_paths(&self) -> Vec<String> {
274 if self.program.contains('/') {
275 return vec![self.program.clone()];
276 }
277 let path = self
278 .env
279 .iter()
280 .rev()
281 .find(|(k, _)| k == "PATH")
282 .map(|(_, v)| v.clone().unwrap_or_default())
283 .or_else(|| (!self.env_clear).then(|| std::env::var("PATH").ok()).flatten())
284 .unwrap_or_else(|| "/bin".into());
285 path.split(':')
286 .filter(|dir| !dir.is_empty())
287 .flat_map(|dir| {
288 let dir = dir.trim_end_matches('/');
289 [format!("{dir}/{}.wasm", self.program), format!("{dir}/{}", self.program)]
290 })
291 .collect()
292 }
293}
294
295fn spec(entries: Vec<(&str, Value)>) -> Vec<u8> {
296 Value::Map(entries.into_iter().map(|(k, v)| (Value::from(k), v)).collect()).encode()
297}
298
299fn search_disks() -> Vec<Option<Address>> {
302 let mut disks = vec![None];
303 let boot = Eeprom::first()
304 .and_then(|eeprom| eeprom.get_data().ok())
305 .and_then(|data| data.as_str().map(|s| Address(s.to_owned())))
306 .filter(|address| !address.as_str().is_empty());
307 let mut rest: Vec<Address> = component::list("filesystem").into_iter().map(|(a, _)| a).collect();
308 if let Some(boot) = boot {
309 rest.retain(|a| *a != boot);
310 disks.push(Some(boot));
311 }
312 disks.extend(rest.into_iter().map(Some));
313 disks
314}
315
316pub fn enter_working_dir() {
321 static ENTERED: Once = Once::new();
322 ENTERED.call_once(|| {
323 if let Ok(dir) = std::env::var("PWD") {
324 if dir.starts_with('/') && dir != "/" {
325 let _ = std::env::set_current_dir(dir);
326 }
327 }
328 });
329}
330
331#[cfg(target_os = "wasi")]
334#[used]
335#[unsafe(link_section = ".init_array")]
336static ENTER_WORKING_DIR: extern "C" fn() = {
337 extern "C" fn enter() {
338 enter_working_dir();
339 }
340 enter
341};
342
343#[derive(Debug)]
345pub struct Child {
346 events: VecDeque<Event>,
347 paused: bool,
349 wants_input: bool,
350 stdin: Vec<u8>,
351 stdin_closed: bool,
352 finished: bool,
353}
354
355impl Child {
356 fn start(spec: &[u8]) -> Result<Option<Child>> {
358 let status = unsafe { sys::spawn_with(spec.as_ptr(), spec.len()) };
359 if status == sys::STATUS_NOT_FOUND {
360 return Ok(None);
361 }
362 let mut child = Child { events: VecDeque::new(), paused: false, wants_input: false, stdin: Vec::new(), stdin_closed: false, finished: false };
363 child.take(status)?;
364 Ok(Some(child))
365 }
366
367 fn take(&mut self, status: i32) -> Result<()> {
369 if status < 0 {
370 self.finished = true;
371 return Err(Error::Failed(String::from_utf8_lossy(&sys::response()).into_owned()));
372 }
373 let items = match Value::decode(&sys::response()) {
374 Some(Value::Array(items)) => items,
375 _ => Vec::new(),
376 };
377 let bytes = |i: usize| items.get(i).and_then(Value::as_bytes).map(<[u8]>::to_vec).unwrap_or_default();
378 self.paused = true;
379 self.wants_input = false;
380 match status {
381 sys::EVENT_OUTPUT => self.events.push_back(Event::Output(bytes(0))),
382 sys::EVENT_INPUT => {
383 self.wants_input = true;
384 self.events.push_back(Event::Input);
385 }
386 sys::EVENT_EXITED | sys::EVENT_CRASHED => {
387 self.finished = true;
388 self.paused = false;
389 let output = bytes(1);
390 if !output.is_empty() {
391 self.events.push_back(Event::Output(output));
392 }
393 let status = if status == sys::EVENT_EXITED {
394 ExitStatus::Exited(items.first().and_then(Value::as_i64).unwrap_or(0) as i32)
395 } else {
396 ExitStatus::Crashed(items.first().and_then(Value::as_str).unwrap_or("crashed").to_owned())
397 };
398 self.events.push_back(Event::Exit(status));
399 }
400 other => return Err(Error::UnexpectedReply(format!("process event {other}"))),
401 }
402 Ok(())
403 }
404
405 pub fn next_event(&mut self) -> Result<Event> {
407 if let Some(event) = self.events.pop_front() {
408 return Ok(event);
409 }
410 if self.finished || !self.paused {
411 return Err(Error::Failed("the process has exited".into()));
412 }
413 let input = std::mem::take(&mut self.stdin);
415 if self.wants_input && input.is_empty() {
416 self.stdin_closed = true;
417 }
418 self.paused = false;
419 let status = unsafe { sys::resume(input.as_ptr(), input.len()) };
420 self.take(status)?;
421 self.events.pop_front().ok_or_else(|| Error::UnexpectedReply("no process event".into()))
422 }
423
424 pub fn write_stdin(&mut self, bytes: &[u8]) {
426 self.stdin.extend_from_slice(bytes);
427 }
428
429 pub fn close_stdin(&mut self) {
431 self.stdin_closed = true;
432 }
433
434 pub fn kill(&mut self) {
436 if !self.finished {
437 unsafe { sys::kill() };
438 self.finished = true;
439 self.paused = false;
440 self.events.clear();
441 }
442 }
443
444 pub fn wait(mut self) -> Result<ExitStatus> {
447 loop {
448 match self.next_event()? {
449 Event::Output(bytes) => {
450 let mut out = std::io::stdout().lock();
451 let _ = out.write_all(&bytes);
452 let _ = out.flush();
453 }
454 Event::Input => {
455 if self.stdin_closed {
456 continue;
457 }
458 let mut buf = [0u8; 4096];
459 match std::io::stdin().read(&mut buf) {
460 Ok(n) if n > 0 => self.write_stdin(&buf[..n]),
461 _ => self.close_stdin(),
462 }
463 }
464 Event::Exit(status) => return Ok(status),
465 }
466 }
467 }
468
469 pub fn wait_with_output(mut self) -> Result<Output> {
472 let mut stdout = Vec::new();
473 loop {
474 match self.next_event()? {
475 Event::Output(bytes) => stdout.extend(bytes),
476 Event::Input => self.close_stdin(),
477 Event::Exit(status) => return Ok(Output { status, stdout }),
478 }
479 }
480 }
481}
482
483impl Drop for Child {
484 fn drop(&mut self) {
485 self.kill();
486 }
487}
488
489#[cfg(test)]
490mod tests {
491 use super::*;
492
493 #[test]
494 fn looks_programs_up_on_path() {
495 let mut cmd = Command::new("cat");
496 cmd.env("PATH", "/bin:/usr/bin/");
497 assert_eq!(cmd.candidate_paths(), ["/bin/cat.wasm", "/bin/cat", "/usr/bin/cat.wasm", "/usr/bin/cat"]);
498 assert_eq!(Command::new("./tools/x.wasm").candidate_paths(), ["./tools/x.wasm"]);
499 let mut bare = Command::new("ls");
500 bare.env_clear();
501 assert_eq!(bare.candidate_paths(), ["/bin/ls.wasm", "/bin/ls"]);
502 }
503
504 #[test]
505 fn builds_the_environment() {
506 let mut cmd = Command::new("x");
507 cmd.env_clear().env("A", "1").env("B", "2").env("A", "3").env_remove("B");
508 assert_eq!(cmd.environment(), ["A=3"]);
509 }
510}