fdio/
spawn_builder.rs

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
162
163
164
165
166
167
168
169
170
171
// Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use crate::{spawn_etc, transfer_fd, SpawnAction, SpawnOptions};

use std::ffi::CString;
use std::fs::File;

#[derive(Default)]
/// Convience wrapper for `spawn_etc`.
pub struct SpawnBuilder {
    options: Option<SpawnOptions>,
    args: Vec<CString>,
    dirs: Vec<(
        CString,
        // Option used for interior mutability. When building the arguments to `spawn_etc` we need
        // borrowed strings and owned handles, so we want this vector to own the strings but allow
        // moving out of the handles.
        //
        // This is always `Some` until the builder is consumed.
        Option<zx::Handle>,
    )>,
}

impl SpawnBuilder {
    /// Create a `SpawnBuilder` with empty `SpawnOptions`.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the `SpawnOptions`.
    pub fn options(mut self, options: SpawnOptions) -> Self {
        self.options = Some(options);
        self
    }

    /// Add an argument.
    pub fn arg(self, arg: impl Into<String>) -> Result<Self, Error> {
        self.arg_impl(arg.into())
    }

    fn arg_impl(mut self, arg: String) -> Result<Self, Error> {
        self.args.push(CString::new(arg).map_err(Error::ConvertArgToCString)?);
        Ok(self)
    }

    /// Add a directory that will be added to the spawned process's namespace.
    pub fn add_dir_to_namespace(self, path: impl Into<String>, dir: File) -> Result<Self, Error> {
        self.add_dir_to_namespace_impl(path.into(), dir)
    }

    fn add_dir_to_namespace_impl(self, path: String, dir: File) -> Result<Self, Error> {
        let handle = transfer_fd(dir).map_err(Error::TransferFd)?;
        self.add_handle_to_namespace(path, handle)
    }

    /// Add a directory that will be added to the spawned process's namespace.
    pub fn add_directory_to_namespace(
        self,
        path: impl Into<String>,
        client_end: fidl::endpoints::ClientEnd<fidl_fuchsia_io::DirectoryMarker>,
    ) -> Result<Self, Error> {
        self.add_directory_to_namespace_impl(path.into(), client_end)
    }

    fn add_directory_to_namespace_impl(
        self,
        path: String,
        client_end: fidl::endpoints::ClientEnd<fidl_fuchsia_io::DirectoryMarker>,
    ) -> Result<Self, Error> {
        self.add_handle_to_namespace(path, client_end.into())
    }

    fn add_handle_to_namespace(mut self, path: String, handle: zx::Handle) -> Result<Self, Error> {
        let path = CString::new(path).map_err(Error::ConvertNamespacePathToCString)?;
        self.dirs.push((path, Some(handle)));
        Ok(self)
    }

    /// Spawn a process from the binary located at `path`.
    pub fn spawn_from_path(
        self,
        path: impl Into<String>,
        job: &zx::Job,
    ) -> Result<zx::Process, Error> {
        self.spawn_from_path_impl(path.into(), job)
    }

    pub fn spawn_from_path_impl(
        mut self,
        path: String,
        job: &zx::Job,
    ) -> Result<zx::Process, Error> {
        let mut actions = self
            .dirs
            .iter_mut()
            .map(|(path, handle)| SpawnAction::add_namespace_entry(path, handle.take().unwrap()))
            .collect::<Vec<_>>();

        spawn_etc(
            job,
            self.options.unwrap_or(SpawnOptions::empty()),
            &CString::new(path).map_err(Error::ConvertBinaryPathToCString)?,
            self.args.iter().map(|arg| arg.as_ref()).collect::<Vec<_>>().as_slice(),
            None,
            actions.as_mut_slice(),
        )
        .map_err(|(status, message)| Error::Spawn { status, message })
    }
}

#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error("failed to convert process argument to CString")]
    ConvertArgToCString(#[source] std::ffi::NulError),

    #[error("failed to convert namespace path to CString")]
    ConvertNamespacePathToCString(#[source] std::ffi::NulError),

    #[error("failed to convert binary path to CString")]
    ConvertBinaryPathToCString(#[source] std::ffi::NulError),

    #[error("failed to transfer_fd")]
    TransferFd(#[source] zx::Status),

    #[error("spawn failed with status: {status} and message: {message}")]
    Spawn { status: zx::Status, message: String },
}

#[cfg(test)]
mod tests {
    use super::*;
    use fidl::AsHandleRef as _;
    use fuchsia_async as fasync;
    use std::io::Write as _;

    async fn process_exit_success(proc: zx::Process) {
        assert_eq!(
            fasync::OnSignals::new(&proc.as_handle_ref(), zx::Signals::PROCESS_TERMINATED)
                .await
                .unwrap(),
            zx::Signals::PROCESS_TERMINATED
        );
        assert_eq!(proc.info().expect("process info").return_code, 0);
    }

    #[fasync::run_singlethreaded(test)]
    async fn spawn_builder() {
        let tempdir = tempfile::TempDir::new().unwrap();
        let () = File::create(tempdir.path().join("injected-file"))
            .unwrap()
            .write_all("some-contents".as_bytes())
            .unwrap();
        let dir = File::open(tempdir.path()).unwrap();

        let builder = SpawnBuilder::new()
            .options(SpawnOptions::DEFAULT_LOADER)
            .arg("arg0")
            .unwrap()
            .arg("arg1")
            .unwrap()
            .add_dir_to_namespace("/injected-dir", dir)
            .unwrap();
        let process = builder
            .spawn_from_path("/pkg/bin/spawn_builder_test_target", &fuchsia_runtime::job_default())
            .unwrap();

        process_exit_success(process).await;
    }
}