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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
extern crate cmake;
#[macro_use]
extern crate failure;
extern crate multimap;
extern crate toml;
use std::borrow::Borrow;
use std::collections::{HashMap, HashSet};
use std::env;
use std::path::{Path, PathBuf};

mod cmake_integration;
mod manifest;
mod types;
// TODO - more selective use of types
pub use cmake_integration::*;
pub use manifest::*;
pub use types::*;

/// Convenience function for getting a quick-working fel4.toml example
pub fn get_exemplar_default_toml() -> &'static str {
    include_str!("../examples/exemplar.toml")
}

/// All the things that could go wrong when reading fel4 configuration data
#[derive(Clone, Debug, Fail, PartialEq)]
pub enum ConfigError {
    #[fail(display = "Unable to read the fel4 manifest file")]
    FileReadFailure,
    #[fail(display = "The fel4 manifest file is unparseable as toml")]
    TomlParseFailure,
    #[fail(display = "The fel4 manifest file is missing the {} table", _0)]
    MissingTable(String),
    #[fail(display = "The fel4 manifest file contained an unexpected table or array {}", _0)]
    UnexpectedStructure(String),
    #[fail(display = "The [{}] table requires the {} property, but it is absent.", _0, _1)]
    MissingRequiredProperty(String, String),
    #[fail(display = "The {} property should be specified as a string, but is not", _0)]
    NonStringProperty(&'static str),
    #[fail(display = "The {} property should be one of {:?}, but is instead {}", _0, _1, _2)]
    InvalidValueOption(&'static str, Vec<String>, String),
    #[fail(
        display = "The fel4 manifest had a duplicate property {} when resolved to a canonical set",
        _0
    )]
    DuplicateProperty(String),
    #[fail(display = "The {} property was supplied, but is not on the permitted whitelist", _0)]
    NonWhitelistProperty(String),
    #[fail(display = "The {} target is not a supported combination with the {} platform", _0, _1)]
    TargetPlatformMismatch(SupportedTarget, SupportedPlatform),
}

/// Returns true if the target and platform are supported to work together
/// Returns false if the pairing is nonsenical or not supported
pub fn is_supported_target_platform_pair(
    target: SupportedTarget,
    platform: SupportedPlatform,
) -> bool {
    match (target, platform) {
        (SupportedTarget::X8664Sel4Fel4, SupportedPlatform::PC99)
        | (SupportedTarget::Armv7Sel4Fel4, SupportedPlatform::Sabre)
        | (SupportedTarget::Aarch64Sel4Fel4, SupportedPlatform::Tx1) => true,
        _ => false,
    }
}

/// Resolve and validate a particular Fel4 configuration for the given
/// `BuildProfile` and the `selected_target` and `selected_platform` found in
/// the `FullFel4Manifest`
pub fn resolve_fel4_config<M: Borrow<FullFel4Manifest>>(
    full: M,
    build_profile: &BuildProfile,
) -> Result<Fel4Config, ConfigError> {
    let selected_target = full.borrow().selected_target;
    let platform = full.borrow().selected_platform;
    if !is_supported_target_platform_pair(selected_target, platform) {
        return Err(ConfigError::TargetPlatformMismatch(
            selected_target,
            platform,
        ));
    }
    let target = full
        .borrow()
        .targets
        .get(&selected_target)
        .ok_or_else(|| ConfigError::MissingTable(selected_target.full_name().to_string()))?;

    let mut properties = HashMap::new();
    add_properties_to_map(&mut properties, &target.direct_properties)?;
    let profile_properties = target
        .build_profile_properties
        .get_vec(build_profile)
        .ok_or_else(|| {
            ConfigError::MissingTable(format!(
                "{}.{}",
                selected_target.full_name(),
                build_profile.full_name()
            ))
        })?;
    add_properties_to_map(&mut properties, profile_properties)?;

    let platform_properties = target
        .platform_properties
        .get_vec(&platform)
        .ok_or_else(|| {
            ConfigError::MissingTable(format!(
                "{}.{}",
                selected_target.full_name(),
                platform.full_name()
            ))
        })?;
    add_properties_to_map(&mut properties, platform_properties)?;

    if let Err(k) = contains_only_whitelisted_property_names(properties.keys()) {
        return Err(ConfigError::NonWhitelistProperty(k.to_string()));
    }

    Ok(Fel4Config {
        artifact_path: full.borrow().artifact_path.clone(),
        target_specs_path: full.borrow().target_specs_path.clone(),
        target: selected_target,
        platform: full.borrow().selected_platform,
        build_profile: *build_profile,
        properties,
    })
}

/// Check an iterator to see if any of its contents are not found in the
/// whitelist of allowed properties.
/// Returns Ok(()) if everything in the iterator is on the whitelist.
/// If a string is found to be not on the whitelist, it is returned as the data
/// in the Err()
pub fn contains_only_whitelisted_property_names<I, T>(iter: I) -> Result<(), String>
where
    I: IntoIterator<Item = T>,
    T: AsRef<str>,
{
    let whitelist: HashSet<String> = ALL_PROPERTIES_WHITELIST
        .iter()
        .map(|s| s.to_string())
        .collect();
    for k in iter {
        if !whitelist.contains(k.as_ref()) {
            return Err(k.as_ref().to_string());
        }
    }
    Ok(())
}

fn add_properties_to_map(
    map: &mut HashMap<String, FlatTomlValue>,
    source: &[FlatTomlProperty],
) -> Result<(), ConfigError> {
    for p in source {
        match map.insert(p.name.clone(), p.value.clone()) {
            None => {}
            Some(_) => return Err(ConfigError::DuplicateProperty(p.name.clone())),
        }
    }
    Ok(())
}

const ALL_PROPERTIES_WHITELIST: &[&str] = &[
    "BuildWithCommonSimulationSettings",
    "KernelOptimisation",
    "KernelVerificationBuild",
    "KernelBenchmarks",
    "KernelFastpath",
    "LibSel4FunctionAttributes",
    "KernelNumDomains",
    "HardwareDebugAPI",
    "KernelColourPrinting",
    "KernelFWholeProgram",
    "KernelResetChunkBits",
    "LibSel4DebugAllocBufferEntries",
    "LibSel4DebugFunctionInstrumentation",
    "KernelNumPriorities",
    "KernelStackBits",
    "KernelTimeSlice",
    "KernelTimerTickMS",
    "KernelUserStackTraceLength",
    "KernelArch",
    "KernelX86Sel4Arch",
    "KernelMaxNumNodes",
    "KernelRetypeFanOutLimit",
    "KernelRootCNodeSizeBits",
    "KernelMaxNumBootinfoUntypedCaps",
    "KernelSupportPCID",
    "KernelCacheLnSz",
    "KernelDebugDisablePrefetchers",
    "KernelExportPMCUser",
    "KernelFPU",
    "KernelFPUMaxRestoresSinceSwitch",
    "KernelFSGSBase",
    "KernelHugePage",
    "KernelIOMMU",
    "KernelIRQController",
    "KernelIRQReporting",
    "KernelLAPICMode",
    "KernelMaxNumIOAPIC",
    "KernelMaxNumWorkUnitsPerPreemption",
    "KernelMultiboot1Header",
    "KernelMultiboot2Header",
    "KernelMultibootGFXMode",
    "KernelSkimWindow",
    "KernelSyscall",
    "KernelVTX",
    "KernelX86DangerousMSR",
    "KernelX86IBPBOnContextSwitch",
    "KernelX86IBRSMode",
    "KernelX86RSBOnContextSwitch",
    "KernelXSaveSize",
    "LinkPageSize",
    "UserLinkerGCSections",
    "KernelX86MicroArch",
    "LibPlatSupportX86ConsoleDevice",
    "KernelDebugBuild",
    "KernelPrinting",
    "KernelArmSel4Arch",
    "KernelAArch32FPUEnableContextSwitch",
    "KernelDebugDisableBranchPrediction",
    "KernelIPCBufferLocation",
    "KernelARMPlatform",
    "ElfloaderImage",
    "ElfloaderMode",
    "ElfloaderErrata764369",
    "KernelArmEnableA9Prefetcher",
    "KernelArmExportPMUUser",
    "KernelDebugDisableL2Cache",
];
/// Things that can go wrong when trying to rely on environment variables
/// to locate the fel4 manifest and its parameterization.
#[derive(Clone, Debug, Fail, PartialEq)]
pub enum ManifestDiscoveryError {
    #[fail(display = "Required environment variable {} was absent", _0)]
    MissingEnvVar(String),
    #[fail(
        display = "The PROFILE environment variable had a value {} that could not be interpreted as a BuildProfile instance",
        _0
    )]
    InvalidBuildProfile(String),
}

/// Read environment variables to discover the information necessary to
/// read and resolve a `Fel4Config`
pub fn infer_manifest_location_from_env() -> Result<(PathBuf, BuildProfile), ManifestDiscoveryError>
{
    let manifest_path = env::var("FEL4_MANIFEST_PATH")
        .map_err(|_| ManifestDiscoveryError::MissingEnvVar("FEL4_MANIFEST_PATH".to_string()))?;
    let raw_profile = env::var("PROFILE")
        .map_err(|_| ManifestDiscoveryError::MissingEnvVar("PROFILE".to_string()))?;
    let build_profile: BuildProfile = raw_profile
        .parse()
        .map_err(ManifestDiscoveryError::InvalidBuildProfile)?;
    Ok((PathBuf::from(manifest_path), build_profile))
}

/// Load, parse, and resolve a Fel4Config
pub fn get_fel4_config<P: AsRef<Path>>(
    fel4_manifest_path: P,
    build_profile: &BuildProfile,
) -> Result<Fel4Config, ConfigError> {
    let full_manifest = get_full_manifest(fel4_manifest_path)?;
    resolve_fel4_config(full_manifest, build_profile)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn infer_manifest_location_from_env_happy_path() {
        std::env::set_var("PROFILE", "debug");
        std::env::set_var("FEL4_MANIFEST_PATH", "./somewhere/else");
        let (p, b) = infer_manifest_location_from_env().expect("Oh no");
        assert_eq!(PathBuf::from("./somewhere/else"), p);
        assert_eq!(BuildProfile::Debug, b);
    }

    #[test]
    fn exemplar_toml_is_fully_valid() {
        let full = parse_full_manifest(get_exemplar_default_toml())
            .expect("Should be able to get the default fel4.toml");
        let _ = resolve_fel4_config(full, &BuildProfile::Debug)
            .expect("Should be able to resolve config");
    }

    #[test]
    fn exemplar_toml_calls_return_identical() {
        let a = get_exemplar_default_toml();
        let b = get_exemplar_default_toml();
        assert_eq!(a, b);
    }

    #[test]
    fn missing_selected_target_get_caught_in_config_resolution() {
        let manifest = parse_full_manifest(
            r#"[fel4]
            target = "x86_64-sel4-fel4"
            platform = "pc99"
            artifact-path = "artifacts/path/nested"
            target-specs-path = "where/are/rust/targets"
            [armv7-sel4-fel4]
            KernelOptimisation = "-O2"
            [armv7-sel4-fel4.debug]
            KernelPrinting = true
            "#,
        ).expect("Should have been able to parse manifest");
        assert_eq!(
            Err(ConfigError::MissingTable("x86_64-sel4-fel4".into())),
            resolve_fel4_config(manifest, &BuildProfile::Debug)
        );
    }

    #[test]
    fn duplicate_property_gets_caught_in_config_resolution() {
        let manifest = parse_full_manifest(
            r#"[fel4]
            target = "x86_64-sel4-fel4"
            platform = "pc99"
            artifact-path = "artifacts/path/nested"
            target-specs-path = "where/are/rust/targets"

            [x86_64-sel4-fel4]
            KernelPrinting = false

            [x86_64-sel4-fel4.debug]
            KernelPrinting = true

            [x86_64-sel4-fel4.pc99]
            KernelX86MicroArch = "nehalem"
            "#,
        ).expect("Should have been able to parse manifest");
        assert_eq!(
            Err(ConfigError::DuplicateProperty("KernelPrinting".into())),
            resolve_fel4_config(manifest, &BuildProfile::Debug)
        );
    }

    #[test]
    fn non_whitelist_property_gets_caught_in_config_resolution() {
        let manifest = parse_full_manifest(
            r#"[fel4]
            target = "x86_64-sel4-fel4"
            platform = "pc99"
            artifact-path = "artifacts/path/nested"
            target-specs-path = "where/are/rust/targets"

            [x86_64-sel4-fel4]
            KernelArch = "x86"

            [x86_64-sel4-fel4.debug]
            KernelPrinting = true

            [x86_64-sel4-fel4.pc99]
            SomeUnallowedProperty = "foo"
            "#,
        ).expect("Should have been able to parse manifest");
        assert_eq!(
            Err(ConfigError::NonWhitelistProperty(
                "SomeUnallowedProperty".into()
            )),
            resolve_fel4_config(manifest, &BuildProfile::Debug)
        );
    }

    #[test]
    fn mismatched_target_platform_pair_gets_caught_in_conflict_resolution() {
        let manifest = parse_full_manifest(
            r#"[fel4]
            target = "x86_64-sel4-fel4"
            platform = "sabre"
            artifact-path = "artifacts/path/nested"
            target-specs-path = "where/are/rust/targets"

            [x86_64-sel4-fel4]
            KernelArch = "x86"

            [x86_64-sel4-fel4.debug]
            KernelPrinting = true

            [x86_64-sel4-fel4.sabre]
            KernelARMPlatform = "sabre"
            "#,
        ).expect("Should have been able to parse manifest");
        assert_eq!(
            Err(ConfigError::TargetPlatformMismatch(
                SupportedTarget::X8664Sel4Fel4,
                SupportedPlatform::Sabre
            )),
            resolve_fel4_config(manifest, &BuildProfile::Debug)
        );
    }
}