builtins/
info_resource.rs

1// Copyright 2020 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use anyhow::{format_err, Error};
6use fidl_fuchsia_kernel as fkernel;
7use futures::prelude::*;
8use std::sync::Arc;
9use zx::{self as zx, HandleBased, Resource};
10
11/// An implementation of fuchsia.kernel.InfoResource protocol.
12pub struct InfoResource {
13    resource: Resource,
14}
15
16impl InfoResource {
17    /// `resource` must be the Info resource.
18    pub fn new(resource: Resource) -> Result<Arc<Self>, Error> {
19        let resource_info = resource.info()?;
20        if resource_info.kind != zx::sys::ZX_RSRC_KIND_SYSTEM
21            || resource_info.base != zx::sys::ZX_RSRC_SYSTEM_INFO_BASE
22            || resource_info.size != 1
23        {
24            return Err(format_err!("Info resource not available."));
25        }
26        Ok(Arc::new(Self { resource }))
27    }
28
29    pub async fn serve(
30        self: Arc<Self>,
31        mut stream: fkernel::InfoResourceRequestStream,
32    ) -> Result<(), Error> {
33        while let Some(fkernel::InfoResourceRequest::Get { responder }) = stream.try_next().await? {
34            responder.send(self.resource.duplicate_handle(zx::Rights::SAME_RIGHTS)?)?;
35        }
36        Ok(())
37    }
38}
39
40#[cfg(test)]
41mod tests {
42    use super::*;
43    use fuchsia_component::client::connect_to_protocol;
44    use {fidl_fuchsia_kernel as fkernel, fuchsia_async as fasync};
45
46    async fn get_info_resource() -> Result<Resource, Error> {
47        let info_resource_provider = connect_to_protocol::<fkernel::InfoResourceMarker>()?;
48        let info_resource_handle = info_resource_provider.get().await?;
49        Ok(Resource::from(info_resource_handle))
50    }
51
52    async fn serve_info_resource() -> Result<fkernel::InfoResourceProxy, Error> {
53        let info_resource = get_info_resource().await?;
54
55        let (proxy, stream) =
56            fidl::endpoints::create_proxy_and_stream::<fkernel::InfoResourceMarker>();
57        fasync::Task::local(
58            InfoResource::new(info_resource)
59                .unwrap_or_else(|e| panic!("Error while creating info resource service: {}", e))
60                .serve(stream)
61                .unwrap_or_else(|e| panic!("Error while serving INFO resource service: {}", e)),
62        )
63        .detach();
64        Ok(proxy)
65    }
66
67    #[fuchsia::test]
68    async fn base_type_is_info() -> Result<(), Error> {
69        let info_resource_provider = serve_info_resource().await?;
70        let info_resource: Resource = info_resource_provider.get().await?;
71        let resource_info = info_resource.info()?;
72        assert_eq!(resource_info.kind, zx::sys::ZX_RSRC_KIND_SYSTEM);
73        assert_eq!(resource_info.base, zx::sys::ZX_RSRC_SYSTEM_INFO_BASE);
74        assert_eq!(resource_info.size, 1);
75        Ok(())
76    }
77}