]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/process/process_fuchsia.rs
Rollup merge of #64935 - AnthonyMikh:librustc_errors/emmiter__code-clarity, r=estebank
[rust.git] / src / libstd / sys / unix / process / process_fuchsia.rs
1 use crate::convert::TryInto;
2 use crate::io;
3 use crate::fmt;
4 use crate::mem;
5 use crate::ptr;
6
7 use crate::sys::process::zircon::{Handle, zx_handle_t};
8 use crate::sys::process::process_common::*;
9
10 use libc::{c_int, size_t};
11
12 ////////////////////////////////////////////////////////////////////////////////
13 // Command
14 ////////////////////////////////////////////////////////////////////////////////
15
16 impl Command {
17     pub fn spawn(&mut self, default: Stdio, needs_stdin: bool)
18                  -> io::Result<(Process, StdioPipes)> {
19         let envp = self.capture_env();
20
21         if self.saw_nul() {
22             return Err(io::Error::new(io::ErrorKind::InvalidInput,
23                                       "nul byte found in provided data"));
24         }
25
26         let (ours, theirs) = self.setup_io(default, needs_stdin)?;
27
28         let process_handle = unsafe { self.do_exec(theirs, envp.as_ref())? };
29
30         Ok((Process { handle: Handle::new(process_handle) }, ours))
31     }
32
33     pub fn exec(&mut self, default: Stdio) -> io::Error {
34         if self.saw_nul() {
35             return io::Error::new(io::ErrorKind::InvalidInput,
36                                   "nul byte found in provided data")
37         }
38
39         match self.setup_io(default, true) {
40             Ok((_, _)) => {
41                 // FIXME: This is tough because we don't support the exec syscalls
42                 unimplemented!();
43             },
44             Err(e) => e,
45         }
46     }
47
48     unsafe fn do_exec(&mut self, stdio: ChildPipes, maybe_envp: Option<&CStringArray>)
49                       -> io::Result<zx_handle_t> {
50         use crate::sys::process::zircon::*;
51
52         let envp = match maybe_envp {
53             // None means to clone the current environment, which is done in the
54             // flags below.
55             None => ptr::null(),
56             Some(envp) => envp.as_ptr(),
57         };
58
59         let make_action = |local_io: &ChildStdio, target_fd| -> io::Result<fdio_spawn_action_t> {
60             if let Some(local_fd) = local_io.fd() {
61                 Ok(fdio_spawn_action_t {
62                     action: FDIO_SPAWN_ACTION_TRANSFER_FD,
63                     local_fd,
64                     target_fd,
65                     ..Default::default()
66                 })
67             } else {
68                 if let ChildStdio::Null = local_io {
69                     // acts as no-op
70                     return Ok(Default::default());
71                 }
72
73                 let mut handle = ZX_HANDLE_INVALID;
74                 let status = fdio_fd_clone(target_fd, &mut handle);
75                 if status == ERR_INVALID_ARGS || status == ERR_NOT_SUPPORTED {
76                     // This descriptor is closed; skip it rather than generating an
77                     // error.
78                     return Ok(Default::default());
79                 }
80                 zx_cvt(status)?;
81
82                 let mut cloned_fd = 0;
83                 zx_cvt(fdio_fd_create(handle, &mut cloned_fd))?;
84
85                 Ok(fdio_spawn_action_t {
86                     action: FDIO_SPAWN_ACTION_TRANSFER_FD,
87                     local_fd: cloned_fd as i32,
88                     target_fd,
89                     ..Default::default()
90                 })
91             }
92         };
93
94         // Clone stdin, stdout, and stderr
95         let action1 = make_action(&stdio.stdin, 0)?;
96         let action2 = make_action(&stdio.stdout, 1)?;
97         let action3 = make_action(&stdio.stderr, 2)?;
98         let actions = [action1, action2, action3];
99
100         // We don't want FileDesc::drop to be called on any stdio. fdio_spawn_etc
101         // always consumes transferred file descriptors.
102         mem::forget(stdio);
103
104         for callback in self.get_closures().iter_mut() {
105             callback()?;
106         }
107
108         let mut process_handle: zx_handle_t = 0;
109         zx_cvt(fdio_spawn_etc(
110             ZX_HANDLE_INVALID,
111             FDIO_SPAWN_CLONE_JOB | FDIO_SPAWN_CLONE_LDSVC | FDIO_SPAWN_CLONE_NAMESPACE
112             | FDIO_SPAWN_CLONE_ENVIRON,  // this is ignored when envp is non-null
113             self.get_argv()[0], self.get_argv().as_ptr(), envp,
114             actions.len() as size_t, actions.as_ptr(),
115             &mut process_handle,
116             ptr::null_mut(),
117         ))?;
118         // FIXME: See if we want to do something with that err_msg
119
120         Ok(process_handle)
121     }
122 }
123
124 ////////////////////////////////////////////////////////////////////////////////
125 // Processes
126 ////////////////////////////////////////////////////////////////////////////////
127
128 pub struct Process {
129     handle: Handle,
130 }
131
132 impl Process {
133     pub fn id(&self) -> u32 {
134         self.handle.raw() as u32
135     }
136
137     pub fn kill(&mut self) -> io::Result<()> {
138         use crate::sys::process::zircon::*;
139
140         unsafe { zx_cvt(zx_task_kill(self.handle.raw()))?; }
141
142         Ok(())
143     }
144
145     pub fn wait(&mut self) -> io::Result<ExitStatus> {
146         use crate::default::Default;
147         use crate::sys::process::zircon::*;
148
149         let mut proc_info: zx_info_process_t = Default::default();
150         let mut actual: size_t = 0;
151         let mut avail: size_t = 0;
152
153         unsafe {
154             zx_cvt(zx_object_wait_one(self.handle.raw(), ZX_TASK_TERMINATED,
155                                       ZX_TIME_INFINITE, ptr::null_mut()))?;
156             zx_cvt(zx_object_get_info(self.handle.raw(), ZX_INFO_PROCESS,
157                                       &mut proc_info as *mut _ as *mut libc::c_void,
158                                       mem::size_of::<zx_info_process_t>(), &mut actual,
159                                       &mut avail))?;
160         }
161         if actual != 1 {
162             return Err(io::Error::new(io::ErrorKind::InvalidData,
163                                       "Failed to get exit status of process"));
164         }
165         Ok(ExitStatus(proc_info.return_code))
166     }
167
168     pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
169         use crate::default::Default;
170         use crate::sys::process::zircon::*;
171
172         let mut proc_info: zx_info_process_t = Default::default();
173         let mut actual: size_t = 0;
174         let mut avail: size_t = 0;
175
176         unsafe {
177             let status = zx_object_wait_one(self.handle.raw(), ZX_TASK_TERMINATED,
178                                             0, ptr::null_mut());
179             match status {
180                 0 => { }, // Success
181                 x if x == ERR_TIMED_OUT => {
182                     return Ok(None);
183                 },
184                 _ => { panic!("Failed to wait on process handle: {}", status); },
185             }
186             zx_cvt(zx_object_get_info(self.handle.raw(), ZX_INFO_PROCESS,
187                                       &mut proc_info as *mut _ as *mut libc::c_void,
188                                       mem::size_of::<zx_info_process_t>(), &mut actual,
189                                       &mut avail))?;
190         }
191         if actual != 1 {
192             return Err(io::Error::new(io::ErrorKind::InvalidData,
193                                       "Failed to get exit status of process"));
194         }
195         Ok(Some(ExitStatus(proc_info.return_code)))
196     }
197 }
198
199 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
200 pub struct ExitStatus(i64);
201
202 impl ExitStatus {
203     pub fn success(&self) -> bool {
204         self.code() == Some(0)
205     }
206
207     pub fn code(&self) -> Option<i32> {
208         // FIXME: support extracting return code as an i64
209         self.0.try_into().ok()
210     }
211
212     pub fn signal(&self) -> Option<i32> {
213         None
214     }
215 }
216
217 impl From<c_int> for ExitStatus {
218     fn from(a: c_int) -> ExitStatus {
219         ExitStatus(a as i64)
220     }
221 }
222
223 impl fmt::Display for ExitStatus {
224     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
225         write!(f, "exit code: {}", self.0)
226     }
227 }