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
// 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.
use {
    fidl_fuchsia_component_resolution as fresolution, fidl_fuchsia_io as fio,
    fuchsia_fs::{file::ReadError, node::OpenError},
    fuchsia_zircon_status::Status,
    thiserror::Error,
    version_history::AbiRevision,
};

#[derive(Error, Debug)]
pub enum AbiRevisionFileError {
    #[error("Failed to decode ABI revision value")]
    Decode,
    #[error("Failed to open ABI revision file: {0}")]
    Open(#[from] OpenError),
    #[error("Failed to read ABI revision file: {0}")]
    Read(#[from] ReadError),
}

impl From<AbiRevisionFileError> for fresolution::ResolverError {
    fn from(err: AbiRevisionFileError) -> fresolution::ResolverError {
        match err {
            AbiRevisionFileError::Open(_) => fresolution::ResolverError::AbiRevisionNotFound,
            AbiRevisionFileError::Read(_) | AbiRevisionFileError::Decode => {
                fresolution::ResolverError::InvalidAbiRevision
            }
        }
    }
}

/// Attempt to read an ABI revision value from the given file path, but do not fail if the file is absent.
pub async fn read_abi_revision_optional(
    dir: &fio::DirectoryProxy,
    path: &str,
) -> Result<Option<AbiRevision>, AbiRevisionFileError> {
    match read_abi_revision(dir, path).await {
        Ok(abi) => Ok(Some(abi)),
        Err(AbiRevisionFileError::Open(OpenError::OpenError(Status::NOT_FOUND))) => Ok(None),
        Err(e) => Err(e),
    }
}

// TODO(https://fxbug.dev/42063073): return fuchsia.version.AbiRevision & use decode_persistent().
/// Read an ABI revision value from the given file path.
async fn read_abi_revision(
    dir: &fio::DirectoryProxy,
    path: &str,
) -> Result<AbiRevision, AbiRevisionFileError> {
    let file = fuchsia_fs::directory::open_file(&dir, path, fio::OpenFlags::RIGHT_READABLE).await?;
    let bytes: [u8; 8] = fuchsia_fs::file::read(&file)
        .await?
        .try_into()
        .map_err(|_| AbiRevisionFileError::Decode)?;
    Ok(AbiRevision::from_bytes(bytes))
}

#[cfg(test)]
mod tests {
    use {
        super::*,
        fuchsia_fs::directory::open_in_namespace,
        std::sync::Arc,
        vfs::{
            directory::entry_container::Directory, execution_scope, file::vmo::read_only,
            pseudo_directory,
        },
    };

    fn serve_dir(root: Arc<impl Directory>) -> fio::DirectoryProxy {
        let (dir_proxy, dir_server) =
            fidl::endpoints::create_proxy::<fio::DirectoryMarker>().unwrap();
        root.open(
            execution_scope::ExecutionScope::new(),
            fio::OpenFlags::RIGHT_READABLE | fio::OpenFlags::DIRECTORY,
            vfs::path::Path::dot().into(),
            fidl::endpoints::ServerEnd::new(dir_server.into_channel()),
        );
        dir_proxy
    }

    fn init_fuchsia_abi_dir(filename: &'static str, content: &'static [u8]) -> fio::DirectoryProxy {
        let dir = pseudo_directory! {
        "meta" => pseudo_directory! {
              "fuchsia.abi" => pseudo_directory! {
                filename => read_only(content),
              }
          }
        };
        serve_dir(dir)
    }

    const ABI_REV_MAX: &'static [u8] = &u64::MAX.to_le_bytes();
    const ABI_REV_ZERO: &'static [u8] = &0u64.to_le_bytes();

    #[fuchsia::test]
    async fn test_read_abi_revision_impl() -> Result<(), AbiRevisionFileError> {
        // Test input that cannot be decoded into a u64 fails
        let dir = init_fuchsia_abi_dir("abi-revision", b"Invalid ABI revision string");
        let res = read_abi_revision_optional(&dir, AbiRevision::PATH).await;
        assert!(matches!(res.unwrap_err(), AbiRevisionFileError::Decode));

        let dir = init_fuchsia_abi_dir("abi-revision", b"");
        let res = read_abi_revision_optional(&dir, AbiRevision::PATH).await;
        assert!(matches!(res.unwrap_err(), AbiRevisionFileError::Decode));

        // Test u64 inputs can be read
        let dir = init_fuchsia_abi_dir("abi-revision", ABI_REV_MAX);
        let res = read_abi_revision_optional(&dir, AbiRevision::PATH).await.unwrap();
        assert_eq!(res, Some(u64::MAX.into()));

        let dir = init_fuchsia_abi_dir("abi-revision", ABI_REV_ZERO);
        let res = read_abi_revision_optional(&dir, AbiRevision::PATH).await.unwrap();
        assert_eq!(res, Some(0u64.into()));

        Ok(())
    }

    #[fuchsia::test]
    async fn test_read_abi_revision_optional_allows_absent_file() -> Result<(), AbiRevisionFileError>
    {
        // Test abi-revision file not found produces Ok(None)
        let dir = init_fuchsia_abi_dir("abi-revision-staging", ABI_REV_MAX);
        let res = read_abi_revision_optional(&dir, AbiRevision::PATH).await.unwrap();
        assert_eq!(res, None);

        Ok(())
    }

    #[fuchsia::test]
    async fn test_read_abi_revision_fails_absent_file() -> Result<(), AbiRevisionFileError> {
        let dir = init_fuchsia_abi_dir("a-different-file", ABI_REV_MAX);
        let err = read_abi_revision(&dir, AbiRevision::PATH).await.unwrap_err();
        assert!(matches!(err, AbiRevisionFileError::Open(OpenError::OpenError(Status::NOT_FOUND))));
        Ok(())
    }

    // Read this test package's ABI revision.
    #[fuchsia::test]
    async fn read_test_pkg_abi_revision() -> Result<(), AbiRevisionFileError> {
        let dir_proxy = open_in_namespace(
            "/pkg",
            fio::OpenFlags::RIGHT_READABLE | fio::OpenFlags::RIGHT_EXECUTABLE,
        )
        .unwrap();
        let abi_revision = read_abi_revision(&dir_proxy, AbiRevision::PATH)
            .await
            .expect("test package doesn't contain an ABI revision");
        version_history::HISTORY
            .check_abi_revision_for_runtime(abi_revision)
            .expect("test package ABI revision should be valid");
        Ok(())
    }
}