component_debug/
capability.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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
// 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::realm::{
    get_all_instances, get_resolved_declaration, GetAllInstancesError, GetDeclarationError,
};
use cm_rust::{
    CapabilityDecl, ComponentDecl, ExposeDecl, ExposeDeclCommon, OfferDecl, OfferDeclCommon,
    SourceName, UseDecl, UseDeclCommon,
};
use fidl_fuchsia_sys2 as fsys;
use moniker::Moniker;
use thiserror::Error;

#[derive(Debug, Error)]
pub enum FindInstancesError {
    #[error("failed to get all instances: {0}")]
    GetAllInstancesError(#[from] GetAllInstancesError),

    #[error("failed to get manifest for {moniker}: {err}")]
    GetDeclarationError {
        moniker: Moniker,
        #[source]
        err: GetDeclarationError,
    },
}

pub enum RouteSegment {
    /// The capability was used by a component instance in its manifest.
    UseBy { moniker: Moniker, capability: UseDecl },

    /// The capability was offered by a component instance in its manifest.
    OfferBy { moniker: Moniker, capability: OfferDecl },

    /// The capability was exposed by a component instance in its manifest.
    ExposeBy { moniker: Moniker, capability: ExposeDecl },

    /// The capability was declared by a component instance in its manifest.
    DeclareBy { moniker: Moniker, capability: CapabilityDecl },
}

impl std::fmt::Display for RouteSegment {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::UseBy { moniker, capability } => {
                write!(
                    f,
                    "`{}` used `{}` from {}",
                    moniker,
                    capability.source_name(),
                    capability.source()
                )
            }
            Self::OfferBy { moniker, capability } => {
                write!(
                    f,
                    "`{}` offered `{}` from {} to {}",
                    moniker,
                    capability.source_name(),
                    capability.source(),
                    capability.target()
                )
            }
            Self::ExposeBy { moniker, capability } => {
                write!(
                    f,
                    "`{}` exposed `{}` from {} to {}",
                    moniker,
                    capability.source_name(),
                    capability.source(),
                    capability.target()
                )
            }
            Self::DeclareBy { moniker, capability } => {
                write!(f, "`{}` declared capability `{}`", moniker, capability.name())
            }
        }
    }
}
/// Find components that reference a capability matching the given |query|.
pub async fn get_all_route_segments(
    query: String,
    realm_query: &fsys::RealmQueryProxy,
) -> Result<Vec<RouteSegment>, FindInstancesError> {
    let instances = get_all_instances(realm_query).await?;
    let mut segments = vec![];

    for instance in instances {
        match get_resolved_declaration(&instance.moniker, realm_query).await {
            Ok(decl) => {
                let mut component_segments = get_segments(&instance.moniker, decl, &query);
                segments.append(&mut component_segments)
            }
            // If the instance is not yet resolved, then we can't get its resolved declaration. If
            // the component doesn't exist, then it's been destroyed since the `get_all_instances`
            // call and we can't get its resolved declaration. Both of these things are expected,
            // so ignore these errors.
            Err(
                GetDeclarationError::InstanceNotResolved(_)
                | GetDeclarationError::InstanceNotFound(_),
            ) => continue,
            Err(err) => {
                return Err(FindInstancesError::GetDeclarationError {
                    moniker: instance.moniker.clone(),
                    err,
                })
            }
        }
    }

    Ok(segments)
}

/// Determine if a capability matching the |query| is declared, exposed, used or offered by
/// this component.
fn get_segments(moniker: &Moniker, manifest: ComponentDecl, query: &str) -> Vec<RouteSegment> {
    let mut segments = vec![];

    for capability in manifest.capabilities {
        if capability.name().to_string().contains(query) {
            segments.push(RouteSegment::DeclareBy { moniker: moniker.clone(), capability });
        }
    }

    for expose in manifest.exposes {
        if expose.source_name().to_string().contains(query) {
            segments.push(RouteSegment::ExposeBy { moniker: moniker.clone(), capability: expose });
        }
    }

    for use_ in manifest.uses {
        if use_.source_name().to_string().contains(query) {
            segments.push(RouteSegment::UseBy { moniker: moniker.clone(), capability: use_ });
        }
    }

    for offer in manifest.offers {
        if offer.source_name().to_string().contains(query) {
            segments.push(RouteSegment::OfferBy { moniker: moniker.clone(), capability: offer });
        }
    }

    segments
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_utils::*;
    use cm_rust::*;
    use cm_rust_testing::*;
    use std::collections::HashMap;

    fn create_realm_query() -> fsys::RealmQueryProxy {
        serve_realm_query(
            vec![fsys::Instance {
                moniker: Some("./my_foo".to_string()),
                url: Some("fuchsia-pkg://fuchsia.com/foo#meta/foo.cm".to_string()),
                instance_id: None,
                resolved_info: Some(fsys::ResolvedInfo {
                    resolved_url: Some("fuchsia-pkg://fuchsia.com/foo#meta/foo.cm".to_string()),
                    execution_info: None,
                    ..Default::default()
                }),
                ..Default::default()
            }],
            HashMap::from([(
                "./my_foo".to_string(),
                ComponentDeclBuilder::new()
                    .child(
                        ChildBuilder::new()
                            .name("my_bar")
                            .url("fuchsia-pkg://fuchsia.com/bar#meta/bar.cm"),
                    )
                    .protocol_default("fuchsia.foo.bar")
                    .use_(UseBuilder::protocol().name("fuchsia.foo.bar"))
                    .expose(
                        ExposeBuilder::protocol()
                            .name("fuchsia.foo.bar")
                            .source(ExposeSource::Self_),
                    )
                    .offer(
                        OfferBuilder::protocol()
                            .name("fuchsia.foo.bar")
                            .source(OfferSource::Self_)
                            .target_static_child("my_bar"),
                    )
                    .build()
                    .native_into_fidl(),
            )]),
            HashMap::new(),
            HashMap::new(),
        )
    }

    #[fuchsia::test]
    async fn segments() {
        let realm_query = create_realm_query();

        let segments =
            get_all_route_segments("fuchsia.foo.bar".to_string(), &realm_query).await.unwrap();

        assert_eq!(segments.len(), 4);

        let mut found_use = false;
        let mut found_offer = false;
        let mut found_expose = false;
        let mut found_declaration = false;

        for segment in segments {
            match segment {
                RouteSegment::UseBy { moniker, capability } => {
                    found_use = true;
                    assert_eq!(moniker, "/my_foo".try_into().unwrap());
                    assert_eq!(
                        capability,
                        UseDecl::Protocol(UseProtocolDecl {
                            source: UseSource::Parent,
                            source_name: "fuchsia.foo.bar".parse().unwrap(),
                            source_dictionary: Default::default(),
                            target_path: "/svc/fuchsia.foo.bar".parse().unwrap(),
                            dependency_type: DependencyType::Strong,
                            availability: Availability::Required
                        })
                    );
                }
                RouteSegment::OfferBy { moniker, capability } => {
                    found_offer = true;
                    assert_eq!(moniker, "/my_foo".try_into().unwrap());
                    assert_eq!(
                        capability,
                        OfferDecl::Protocol(OfferProtocolDecl {
                            source: OfferSource::Self_,
                            source_name: "fuchsia.foo.bar".parse().unwrap(),
                            source_dictionary: Default::default(),
                            target: OfferTarget::Child(ChildRef {
                                name: "my_bar".parse().unwrap(),
                                collection: None,
                            }),
                            target_name: "fuchsia.foo.bar".parse().unwrap(),
                            dependency_type: DependencyType::Strong,
                            availability: Availability::Required
                        })
                    );
                }
                RouteSegment::ExposeBy { moniker, capability } => {
                    found_expose = true;
                    assert_eq!(moniker, "/my_foo".try_into().unwrap());
                    assert_eq!(
                        capability,
                        ExposeDecl::Protocol(ExposeProtocolDecl {
                            source: ExposeSource::Self_,
                            source_name: "fuchsia.foo.bar".parse().unwrap(),
                            source_dictionary: Default::default(),
                            target: ExposeTarget::Parent,
                            target_name: "fuchsia.foo.bar".parse().unwrap(),
                            availability: Availability::Required
                        })
                    );
                }
                RouteSegment::DeclareBy { moniker, capability } => {
                    found_declaration = true;
                    assert_eq!(moniker, "/my_foo".try_into().unwrap());
                    assert_eq!(
                        capability,
                        CapabilityDecl::Protocol(ProtocolDecl {
                            name: "fuchsia.foo.bar".parse().unwrap(),
                            source_path: Some("/svc/fuchsia.foo.bar".parse().unwrap()),
                            delivery: Default::default(),
                        })
                    );
                }
            }
        }

        assert!(found_use);
        assert!(found_expose);
        assert!(found_offer);
        assert!(found_declaration);
    }
}