block_adapter/
lib.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
172
173
174
175
176
// Copyright 2022 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.

// This launches the binary specified in the arguments and takes the block device that is passed via
// the usual startup handle and makes it appear to the child process as an object that will work
// with POSIX I/O.  The object will exist in the child's namespace under /device/block.  At the time
// of writing, this is used to run the fsck-msdosfs and mkfs-msdosfs tools which use POSIX I/O to
// interact with block devices.

use anyhow::Error;
use block_client::{BlockClient as _, BufferSlice, MutableBufferSlice, RemoteBlockClient};
use fidl::endpoints::{create_endpoints, ServerEnd};
use std::sync::Arc;
use vfs::directory::entry::{DirectoryEntry, EntryInfo, GetEntryInfo, OpenRequest};
use vfs::directory::entry_container::Directory;
use vfs::execution_scope::ExecutionScope;
use vfs::file::{FidlIoConnection, File, FileIo, FileLike, FileOptions, SyncMode};
use vfs::node::Node;
use vfs::path::Path;
use vfs::{immutable_attributes, pseudo_directory, ObjectRequestRef};
use {
    fidl_fuchsia_hardware_block as fhardware_block, fidl_fuchsia_io as fio, fuchsia_async as fasync,
};

struct BlockFile {
    block_client: RemoteBlockClient,
}

impl DirectoryEntry for BlockFile {
    fn open_entry(self: Arc<Self>, request: OpenRequest<'_>) -> Result<(), zx::Status> {
        request.open_file(self)
    }
}

impl GetEntryInfo for BlockFile {
    fn entry_info(&self) -> EntryInfo {
        EntryInfo::new(0, fio::DirentType::File)
    }
}

impl Node for BlockFile {
    async fn get_attributes(
        &self,
        requested_attributes: fio::NodeAttributesQuery,
    ) -> Result<fio::NodeAttributes2, zx::Status> {
        let block_size = self.block_client.block_size();
        let block_count = self.block_client.block_count();
        let device_size = block_count.checked_mul(block_size.into()).unwrap();
        Ok(immutable_attributes!(
            requested_attributes,
            Immutable {
                protocols: fio::NodeProtocolKinds::FILE,
                abilities: fio::Operations::GET_ATTRIBUTES
                    | fio::Operations::UPDATE_ATTRIBUTES
                    | fio::Operations::READ_BYTES
                    | fio::Operations::WRITE_BYTES,
                content_size: device_size,
                storage_size: device_size,
            }
        ))
    }
}

impl File for BlockFile {
    fn writable(&self) -> bool {
        true
    }

    async fn open_file(&self, _options: &FileOptions) -> Result<(), zx::Status> {
        Ok(())
    }

    async fn truncate(&self, _length: u64) -> Result<(), zx::Status> {
        Err(zx::Status::NOT_SUPPORTED)
    }

    async fn get_backing_memory(&self, _flags: fio::VmoFlags) -> Result<zx::Vmo, zx::Status> {
        Err(zx::Status::NOT_SUPPORTED)
    }

    async fn get_size(&self) -> Result<u64, zx::Status> {
        let block_size = self.block_client.block_size();
        let block_count = self.block_client.block_count();
        Ok(block_count.checked_mul(block_size.into()).unwrap())
    }

    async fn update_attributes(
        &self,
        _attributes: fio::MutableNodeAttributes,
    ) -> Result<(), zx::Status> {
        Err(zx::Status::NOT_SUPPORTED)
    }

    async fn sync(&self, _mode: SyncMode) -> Result<(), zx::Status> {
        self.block_client.flush().await
    }
}

impl FileIo for BlockFile {
    async fn read_at(&self, offset: u64, buffer: &mut [u8]) -> Result<u64, zx::Status> {
        let () = self.block_client.read_at(MutableBufferSlice::Memory(buffer), offset).await?;
        Ok(buffer.len().try_into().unwrap())
    }

    async fn write_at(&self, offset: u64, content: &[u8]) -> Result<u64, zx::Status> {
        let () = self.block_client.write_at(BufferSlice::Memory(content), offset).await?;
        Ok(content.len().try_into().unwrap())
    }

    async fn append(&self, _content: &[u8]) -> Result<(u64, u64), zx::Status> {
        Err(zx::Status::NOT_SUPPORTED)
    }
}

impl FileLike for BlockFile {
    fn open(
        self: Arc<Self>,
        scope: ExecutionScope,
        options: FileOptions,
        object_request: ObjectRequestRef<'_>,
    ) -> Result<(), zx::Status> {
        FidlIoConnection::spawn(scope, self, options, object_request)
    }
}

// This launches the binary specified in the arguments and takes a block device and makes it appear
// to the child process as an object that will work with POSIX I/O.  The object will exist in the
// child's namespace under /device/block.  At the time of writing, this is used to run the
// fsck-msdosfs and mkfs-msdosfs tools which use POSIX I/O to interact with block devices.
pub async fn run(
    block_proxy: fhardware_block::BlockProxy,
    binary: &str,
    args: impl Iterator<Item = String>,
) -> Result<i64, Error> {
    let (client, server) = create_endpoints::<fio::DirectoryMarker>();

    let server_fut = {
        let block_client = RemoteBlockClient::new(block_proxy).await?;
        let dir = pseudo_directory! {
            "block" => Arc::new(BlockFile {
                block_client,
            }),
        };

        let scope = ExecutionScope::new();
        let () = dir.open(
            scope.clone(),
            fio::OpenFlags::RIGHT_READABLE | fio::OpenFlags::RIGHT_WRITABLE,
            Path::dot(),
            ServerEnd::new(server.into_channel()),
        );
        async move { scope.wait().await }
    };

    let client_fut = {
        let mut builder = fdio::SpawnBuilder::new()
            .options(fdio::SpawnOptions::CLONE_ALL)
            .add_directory_to_namespace("/device", client)?
            .arg(binary)?;
        for arg in args {
            builder = builder.arg(arg)?;
        }
        builder = builder.arg("/device/block")?;
        let process = builder.spawn_from_path(binary, &fuchsia_runtime::job_default())?;

        async move {
            let _: zx::Signals =
                fasync::OnSignals::new(&process, zx::Signals::PROCESS_TERMINATED).await?;
            let info = process.info()?;
            Ok::<_, Error>(info.return_code)
        }
    };

    futures::future::join(server_fut, client_fut).await.1
}