Skip to main content

rucc_driver/
install.rs

1//! Checking a sysroot artifact and putting it in the cache.
2//!
3//! Design: `spec/cross-compile/13-distribution.md` section 13.8, which divides a fetch in two. A
4//! downloader the machine already has moves the bytes, and everything that decides whether the
5//! result is correct is here. That division is why this file has no URL in it and runs no network
6//! code: what it is handed is a file on disk and the hash that file is supposed to have.
7//!
8//! # The order, which is the whole of the argument
9//!
10//! The hash of the archive is checked before anything is unpacked. So what `tar` is pointed at is
11//! always a file we have already identified, and an unpacker's behaviour on a file somebody else
12//! chose is not a question this has to have an answer to.
13//!
14//! Then the files that came out are checked against the manifest the producer put in the archive,
15//! in both directions. Every line has to name a file with the sha256 it recorded, and every file
16//! has to be named by a line. The second direction is the one that is easy to leave out and it is
17//! the one that matters: [`rucc_sysroot::Manifest::digest`] is a claim about what is under a
18//! directory, and a file nobody recorded makes it a claim about less than what is there.
19//!
20//! The manifest is the producer's rather than ours because of what is in it. An input carries a
21//! source, a URL and a licence, and a walk of a directory tree knows none of the three. The
22//! producer in `tamnd/rucc-cross` knows all of them, so it writes the record and this checks it
23//! against the bytes, which is the same shape as section 13.6's rule about a generated artifact
24//! being checked against its generator.
25//!
26//! Only then is the result renamed into place, which is section 13.2's concurrency rule. The
27//! staging directory is inside the cache so that the rename is a rename and not a copy, because
28//! the two paths are on one filesystem by construction.
29
30use std::fs;
31use std::io;
32use std::path::{Component, Path, PathBuf};
33use std::process::Command;
34use std::time::{SystemTime, UNIX_EPOCH};
35
36use rucc_sysroot::{Kernel, KernelManifest, Manifest, Sysroot, sha256};
37use rucc_tuple::TargetTuple;
38
39use crate::{CliError, err};
40
41/// What was at the destination before an install put something there.
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub enum Before {
44    /// Nothing, which is the first install of this target on this machine.
45    Nothing,
46    /// A sysroot whose manifest has the same digest, so the install was not needed and nothing was
47    /// moved. Two rucc versions share a directory for the reason section 13.2 gives, and a second
48    /// fetch of the same artifact is the ordinary way this happens.
49    TheSame,
50    /// A sysroot with a different digest, which was replaced. The string is the digest that was
51    /// there, so that whatever reports the install can say what it stood on.
52    Different(String),
53}
54
55/// What an install left behind.
56#[derive(Debug, Clone, PartialEq, Eq)]
57pub struct Installed {
58    /// Where it is, which is `sysroots/<tuple>` under the cache, or `kernel-headers` for the tree
59    /// every Linux target shares.
60    pub root: PathBuf,
61    /// The digest of its manifest, which is what `rucc -print-sysroot-digest` prints for it.
62    pub digest: String,
63    /// How many files the manifest records, all of which were checked.
64    pub files: usize,
65    /// What the destination held before this.
66    pub before: Before,
67}
68
69/// Check a file against the hash it is supposed to have.
70///
71/// The hash comes from the rucc release rather than from the artifact or from the server that
72/// served it, which is the only arrangement where a check means anything. Section 13.2 says a
73/// mismatch is a hard failure with no override flag, so there is no argument here that could turn
74/// one into a warning.
75///
76/// # Errors
77///
78/// A file that cannot be read, and a hash that does not match. The message names both hashes,
79/// because the first thing anybody does with a mismatch is ask whether they downloaded the wrong
80/// thing or the right thing badly, and the two look different.
81pub fn verify(archive: &Path, expected: &str) -> Result<(), CliError> {
82    let bytes = fs::read(archive).map_err(|why| err(format!("{}: {why}", archive.display())))?;
83    let found = sha256::hex(&bytes);
84    if found == expected {
85        return Ok(());
86    }
87    Err(err(format!(
88        "{} has sha256 {found} where this release pins {expected}, so it is not the artifact this \
89         build knows about",
90        archive.display()
91    )))
92}
93
94/// Check an artifact and install it as the sysroot for a target.
95///
96/// The steps are ยง13.8's, in order: the hash, the unpack, the manifest against the tree and the
97/// tree against the manifest, the rename. Nothing is written outside the cache and nothing outside
98/// the cache is read except the archive.
99///
100/// # Errors
101///
102/// Every step, and each message says which step. An artifact for the wrong target, a missing
103/// manifest, a file whose hash disagrees with the record, a file no line names, and anything the
104/// filesystem or `tar` refuses. A failure leaves the destination as it was: the work happens in a
105/// staging directory and the last thing that happens is the rename.
106pub fn install(
107    archive: &Path,
108    expected: &str,
109    target: TargetTuple,
110    cache: &Path,
111) -> Result<Installed, CliError> {
112    verify(archive, expected)?;
113    staged(cache, &target.to_canonical_string(), |staging| {
114        install_staged(archive, target, cache, staging)
115    })
116}
117
118/// Check the kernel header tree's artifact and install it where every Linux target reads it.
119///
120/// The same four steps as [`install`], against the tree's own record rather than a sysroot's. What
121/// is not checked is that the tree is the release a sysroot's `kernel` line names, for the reason
122/// [`rucc_sysroot::Kernel`] gives: the two are produced by two commands and can be paired either way,
123/// and the records are what make a stale pairing visible.
124///
125/// # Errors
126///
127/// The same as [`install`]'s, with a record that is not a kernel tree's in place of a sysroot for
128/// the wrong target.
129pub fn install_kernel(archive: &Path, expected: &str, cache: &Path) -> Result<Installed, CliError> {
130    verify(archive, expected)?;
131    staged(cache, "kernel-headers", |staging| install_kernel_staged(archive, cache, staging))
132}
133
134/// Run an install in a staging directory of its own, and take the directory away if it fails.
135///
136/// Every exit has to take the staging directory with it, including the ones that are somebody
137/// else's fault, or a machine that fetches a broken artifact twice a day fills its cache with half
138/// unpacked trees.
139fn staged(
140    cache: &Path,
141    name: &str,
142    work: impl FnOnce(&Path) -> Result<Installed, CliError>,
143) -> Result<Installed, CliError> {
144    let staging = staging_dir(cache, name);
145    fs::create_dir_all(&staging).map_err(|why| err(format!("{}: {why}", staging.display())))?;
146    let outcome = work(&staging);
147    if outcome.is_err() {
148        let _ = fs::remove_dir_all(&staging);
149    }
150    outcome
151}
152
153/// The record at the top of an unpacked archive, as text.
154fn record(archive: &Path, staging: &Path) -> Result<String, CliError> {
155    let record = staging.join("manifest");
156    fs::read_to_string(&record).map_err(|why| {
157        if why.kind() == io::ErrorKind::NotFound {
158            err(format!(
159                "{} has no manifest in it, so there is nothing to check its files against",
160                archive.display()
161            ))
162        } else {
163            err(format!("{}: {why}", record.display()))
164        }
165    })
166}
167
168/// The install, with the staging directory already made and cleaned up by the caller.
169fn install_staged(
170    archive: &Path,
171    target: TargetTuple,
172    cache: &Path,
173    staging: &Path,
174) -> Result<Installed, CliError> {
175    unpack(archive, staging)?;
176    let text = record(archive, staging)?;
177    let manifest =
178        Manifest::parse(&text).map_err(|why| err(format!("{}: {why}", archive.display())))?;
179
180    if manifest.target() != target {
181        return Err(err(format!(
182            "{} is a sysroot for {}, which is not {}",
183            archive.display(),
184            manifest.target().to_canonical_string(),
185            target.to_canonical_string()
186        )));
187    }
188
189    let recorded: Vec<(&str, &str)> = manifest
190        .inputs()
191        .iter()
192        .map(|input| (input.path.as_str(), input.sha256.as_str()))
193        .collect();
194    check(staging, &recorded).map_err(|why| err(format!("{}: {why}", archive.display())))?;
195
196    let digest = manifest.digest();
197    let root = Sysroot::in_cache(cache, target).root().to_path_buf();
198    let before = swap(staging, &root, &digest, existing(&root))?;
199    Ok(Installed { root, digest, files: recorded.len(), before })
200}
201
202/// The kernel tree's install, with the staging directory already made and cleaned up by the
203/// caller.
204fn install_kernel_staged(
205    archive: &Path,
206    cache: &Path,
207    staging: &Path,
208) -> Result<Installed, CliError> {
209    unpack(archive, staging)?;
210    let text = record(archive, staging)?;
211    let manifest =
212        KernelManifest::parse(&text).map_err(|why| err(format!("{}: {why}", archive.display())))?;
213
214    let recorded: Vec<(&str, &str)> =
215        manifest.files().iter().map(|file| (file.path.as_str(), file.sha256.as_str())).collect();
216    check(staging, &recorded).map_err(|why| err(format!("{}: {why}", archive.display())))?;
217
218    let digest = manifest.digest();
219    let root = Kernel::in_cache(cache);
220    let before = swap(staging, &root, &digest, existing_kernel(&root))?;
221    Ok(Installed { root, digest, files: recorded.len(), before })
222}
223
224/// Where this install does its work.
225///
226/// Inside the cache, because the rename at the end is only atomic if the two paths are on one
227/// filesystem, and a name nothing else will pick, because two builds fetching the same target at
228/// the same time is the ordinary case rather than the unlucky one. The process id is not enough on
229/// its own: one process can install the same target twice.
230fn staging_dir(cache: &Path, name: &str) -> PathBuf {
231    let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default();
232    let unique = format!("{name}-{}-{}", std::process::id(), now.as_nanos());
233    cache.join("staging").join(unique)
234}
235
236/// Unpack a verified archive with the platform's own `tar`.
237///
238/// Section 13.8's decision keeps an archive reader out of the compiler for the same reason it keeps
239/// a TLS stack out, and `tar` is on every host in the support table, including Windows since 1803.
240/// The members are unpacked as they are, with no component stripped, because the staging directory
241/// is one we made for this and a single directory inside the archive would only be a name to
242/// disagree about.
243fn unpack(archive: &Path, into: &Path) -> Result<(), CliError> {
244    let output =
245        Command::new("tar").arg("-xzf").arg(archive).arg("-C").arg(into).output().map_err(
246            |why| err(format!("could not run `tar`, which is how an artifact is unpacked: {why}")),
247        )?;
248    if output.status.success() {
249        return Ok(());
250    }
251    let said = String::from_utf8_lossy(&output.stderr);
252    let said = said.trim();
253    let detail = if said.is_empty() { String::new() } else { format!(": {said}") };
254    Err(err(format!("`tar` could not unpack {}{detail}", archive.display())))
255}
256
257/// Check a tree against a record and the record against the tree.
258///
259/// The record is the path and the sha256 of every file, which is the part a sysroot's manifest and
260/// the kernel tree's have in common.
261///
262/// The errors are collected rather than returned one at a time. An artifact that fails this is
263/// either the wrong artifact or a broken producer, and which of the two it is shows in how many
264/// files disagree, so a report that stopped at the first one would hide the thing that tells them
265/// apart.
266fn check(tree: &Path, files: &[(&str, &str)]) -> Result<(), String> {
267    let mut problems: Vec<String> = Vec::new();
268    let mut recorded: Vec<&str> = Vec::new();
269
270    for &(path, sha256) in files {
271        recorded.push(path);
272        let at = match relative(tree, path) {
273            Ok(at) => at,
274            Err(why) => {
275                problems.push(why);
276                continue;
277            }
278        };
279        match fs::read(&at) {
280            Ok(bytes) => {
281                let found = sha256::hex(&bytes);
282                if found != sha256 {
283                    problems
284                        .push(format!("{path} has sha256 {found} where the record says {sha256}"));
285                }
286            }
287            Err(why) if why.kind() == io::ErrorKind::NotFound => {
288                problems.push(format!("{path} is in the record and not in the archive"));
289            }
290            Err(why) => problems.push(format!("{path}: {why}")),
291        }
292    }
293
294    let mut found = Vec::new();
295    walk(tree, String::new(), &mut found).map_err(|why| format!("{}: {why}", tree.display()))?;
296    recorded.sort_unstable();
297    for path in &found {
298        // The manifest is the record and is not a line in itself, which is the one file in a
299        // sysroot that is allowed to be there without being recorded.
300        if path == "manifest" {
301            continue;
302        }
303        if recorded.binary_search(&path.as_str()).is_err() {
304            problems.push(format!("{path} is in the archive and not in the record"));
305        }
306    }
307
308    if problems.is_empty() {
309        return Ok(());
310    }
311    problems.sort();
312    let first = &problems[0];
313    if problems.len() == 1 {
314        return Err(format!("the archive does not match its own manifest: {first}"));
315    }
316    Err(format!(
317        "the archive does not match its own manifest: {first}, and {} more files disagree",
318        problems.len() - 1
319    ))
320}
321
322/// The path a recorded input names, refusing one that is not under the tree.
323///
324/// A manifest is checked before it is trusted and a path is part of a manifest. `..` in a recorded
325/// path, or a path that starts at the root of the filesystem, would write the check against a file
326/// the archive never carried, so neither is a path this reads.
327fn relative(tree: &Path, path: &str) -> Result<PathBuf, String> {
328    let candidate = Path::new(path);
329    let ordinary = candidate.components().all(|part| matches!(part, Component::Normal(_)));
330    if !ordinary {
331        return Err(format!("{path} is not a path inside a sysroot"));
332    }
333    Ok(tree.join(candidate))
334}
335
336/// Every file under a directory, as paths relative to it with `/` between the parts.
337///
338/// `/` whatever the host separator is, because that is the spelling a manifest uses and the
339/// comparison is against a manifest. A symlink is a leaf rather than something to follow: following
340/// one would count a file twice, or walk forever, and what a recorded hash is about is the bytes a
341/// compiler reads through that name, which `fs::read` gets by following it once.
342fn walk(dir: &Path, prefix: String, out: &mut Vec<String>) -> io::Result<()> {
343    for entry in fs::read_dir(dir)? {
344        let entry = entry?;
345        let name = entry.file_name().to_string_lossy().into_owned();
346        let path = if prefix.is_empty() { name } else { format!("{prefix}/{name}") };
347        if entry.file_type()?.is_dir() {
348            walk(&entry.path(), path, out)?;
349        } else {
350            out.push(path);
351        }
352    }
353    Ok(())
354}
355
356/// Put the staged tree where a compiler will look for it.
357///
358/// Section 13.2 asks for an atomic rename and never an in place mutation, which is a rule about
359/// what a parallel build sees. A compile that is reading the old sysroot while this happens keeps
360/// reading the files it has open, and one that starts during the swap finds either the old tree or
361/// the new one.
362///
363/// An existing tree with the same digest is left alone. That is not an optimization: a second fetch
364/// of the same artifact is the ordinary case, and replacing a directory that is already correct
365/// would move files under a build for no reason at all.
366fn swap(
367    staging: &Path,
368    root: &Path,
369    digest: &str,
370    there: Option<String>,
371) -> Result<Before, CliError> {
372    let before = match there {
373        Some(found) if found == digest => {
374            let _ = fs::remove_dir_all(staging);
375            return Ok(Before::TheSame);
376        }
377        Some(found) => Before::Different(found),
378        None => Before::Nothing,
379    };
380
381    if let Some(parent) = root.parent() {
382        fs::create_dir_all(parent).map_err(|why| err(format!("{}: {why}", parent.display())))?;
383    }
384
385    // The old tree is moved aside rather than deleted first. Deleting it first would leave the path
386    // missing for as long as the delete takes, which on a sysroot is thousands of files, and the
387    // window this way is one rename wide.
388    let aside = root.with_extension(format!("old.{}", std::process::id()));
389    if before != Before::Nothing {
390        let _ = fs::remove_dir_all(&aside);
391        fs::rename(root, &aside)
392            .map_err(|why| err(format!("could not move {} aside: {why}", root.display())))?;
393    }
394    let renamed = fs::rename(staging, root);
395    if let Err(why) = renamed {
396        // Put back what was there. A failed install that also took the working sysroot away would
397        // be worse than the failure it started as.
398        if before != Before::Nothing {
399            let _ = fs::rename(&aside, root);
400        }
401        return Err(err(format!("could not put {} in place: {why}", root.display())));
402    }
403    if before != Before::Nothing {
404        let _ = fs::remove_dir_all(&aside);
405    }
406    Ok(before)
407}
408
409/// The digest of the sysroot that is already at this path, if there is one with a manifest.
410///
411/// A directory with no manifest in it answers [`None`] and is replaced like anything else. It is
412/// either a tree somebody assembled by hand, which `--sysroot` is the flag for and the cache is not
413/// the place for, or the wreckage of an install from before this code existed.
414fn existing(root: &Path) -> Option<String> {
415    let text = fs::read_to_string(root.join("manifest")).ok()?;
416    Manifest::parse(&text).ok().map(|manifest| manifest.digest())
417}
418
419/// The same question about the kernel tree, whose record is in its own format.
420fn existing_kernel(root: &Path) -> Option<String> {
421    let text = fs::read_to_string(root.join("manifest")).ok()?;
422    KernelManifest::parse(&text).ok().map(|manifest| manifest.digest())
423}
424
425#[cfg(test)]
426mod tests {
427    use super::{Before, Installed, check, install, install_kernel, relative, verify, walk};
428    use rucc_sysroot::{Input, KernelFile, KernelManifest, Licence, Manifest, Provenance, sha256};
429    use rucc_tuple::{TargetTuple, Version};
430    use std::path::{Path, PathBuf};
431    use std::process::Command;
432
433    /// A directory that goes away with the test, and the files in it.
434    struct Tree(PathBuf);
435
436    impl Drop for Tree {
437        fn drop(&mut self) {
438            let _ = std::fs::remove_dir_all(&self.0);
439        }
440    }
441
442    impl Tree {
443        fn new(name: &str) -> Tree {
444            let dir =
445                std::env::temp_dir().join(format!("rucc-install-{}-{name}", std::process::id()));
446            let _ = std::fs::remove_dir_all(&dir);
447            std::fs::create_dir_all(&dir).expect("a temporary directory should be writable");
448            Tree(dir)
449        }
450
451        fn write(&self, path: &str, text: &str) {
452            let at = self.0.join(path);
453            if let Some(parent) = at.parent() {
454                std::fs::create_dir_all(parent).expect("a subdirectory should be creatable");
455            }
456            std::fs::write(&at, text).expect("a temporary file should be writable");
457        }
458    }
459
460    /// The target every test here uses, and a musl one so that nothing depends on the host.
461    fn target() -> TargetTuple {
462        "x86_64-linux-musl".parse().expect("a tuple the table knows")
463    }
464
465    /// A manifest for these files, with their real hashes in it.
466    fn manifest_for(files: &[(&str, &str)]) -> Manifest {
467        let mut manifest = Manifest::new(target());
468        for (path, text) in files {
469            manifest.push(Input {
470                path: (*path).to_owned(),
471                source: "musl-1.2.5".to_owned(),
472                url: "https://musl.libc.org/releases/musl-1.2.5.tar.gz".to_owned(),
473                sha256: sha256::hex(text.as_bytes()),
474                licence: Licence::Mit,
475                provenance: Provenance::Bundled,
476            });
477        }
478        manifest
479    }
480
481    /// An artifact holding these files and a manifest that describes them, and its sha256.
482    ///
483    /// Built with the same `tar` the install unpacks with, which is the point: a test that wrote its
484    /// own archive format would be testing a reader nobody uses.
485    fn artifact(tree: &Tree, files: &[(&str, &str)], manifest: &Manifest) -> (PathBuf, String) {
486        artifact_with(tree, files, &manifest.render())
487    }
488
489    /// The same, with the record already rendered, which is how the kernel tree's is passed.
490    fn artifact_with(tree: &Tree, files: &[(&str, &str)], record: &str) -> (PathBuf, String) {
491        let staged = tree.0.join("staged");
492        std::fs::create_dir_all(&staged).expect("a staging directory should be creatable");
493        for (path, text) in files {
494            let at = staged.join(path);
495            if let Some(parent) = at.parent() {
496                std::fs::create_dir_all(parent).expect("a subdirectory should be creatable");
497            }
498            std::fs::write(&at, text).expect("a file should be writable");
499        }
500        std::fs::write(staged.join("manifest"), record).expect("the manifest should be writable");
501
502        let archive = tree.0.join("artifact.tar.gz");
503        let status = Command::new("tar")
504            .arg("-czf")
505            .arg(&archive)
506            .arg("-C")
507            .arg(&staged)
508            .arg(".")
509            .status()
510            .expect("tar should be on a machine that runs these tests");
511        assert!(status.success(), "tar should be able to write an archive");
512        std::fs::remove_dir_all(&staged).expect("the staged tree should be removable");
513
514        let bytes = std::fs::read(&archive).expect("the archive should be readable");
515        let hash = sha256::hex(&bytes);
516        (archive, hash)
517    }
518
519    const FILES: &[(&str, &str)] =
520        &[("include/stdio.h", "int puts(const char *);\n"), ("lib/libc.so", "not really\n")];
521
522    #[test]
523    fn an_artifact_that_matches_its_record_is_installed() {
524        let tree = Tree::new("good");
525        let manifest = manifest_for(FILES);
526        let (archive, hash) = artifact(&tree, FILES, &manifest);
527        let cache = tree.0.join("cache");
528
529        let done = install(&archive, &hash, target(), &cache).expect("this one should install");
530        assert_eq!(done.before, Before::Nothing);
531        assert_eq!(done.files, 2);
532        assert_eq!(done.digest, manifest.digest());
533        assert_eq!(done.root, cache.join("sysroots").join("x86_64-linux-musl"));
534
535        // The files are where a compiler looks for them, and the record is beside them, which is
536        // what `-print-sysroot-provenance` reads.
537        assert!(done.root.join("include/stdio.h").is_file());
538        assert_eq!(
539            std::fs::read_to_string(done.root.join("manifest")).expect("a manifest"),
540            manifest.render()
541        );
542        // And nothing is left in the staging area, which is a cache that would otherwise grow a
543        // copy of every sysroot it ever installed.
544        let left: Vec<PathBuf> = std::fs::read_dir(cache.join("staging"))
545            .expect("the staging directory")
546            .map(|entry| entry.expect("an entry").path())
547            .collect();
548        assert_eq!(left, Vec::<PathBuf>::new(), "a staging tree was left behind");
549    }
550
551    /// `--fetch` from end to end, with the artifact already where a downloader would have put it.
552    ///
553    /// No downloader runs, and that is the case rather than a way around one: section 13.8 says a
554    /// machine with none of the three is told the path to put a file at and a second run carries on
555    /// from the check, so this is that machine. What it tests is that the table, the check, the
556    /// unpack and the rename are wired to each other, which is the one thing neither module's own
557    /// tests can see.
558    ///
559    /// It is here rather than beside the parser because the fixtures for an artifact are here, and a
560    /// second copy of them next door is the thing most likely to drift away from this one.
561    #[test]
562    fn a_fetch_of_an_artifact_that_is_already_on_the_machine_installs_it() {
563        let tree = Tree::new("fetch");
564        let manifest = manifest_for(FILES);
565        let (built, hash) = artifact(&tree, FILES, &manifest);
566        let cache = tree.0.join("cache");
567
568        // A table row names an artifact by a URL and a hash, and both are static strings there
569        // because a release is what writes them. A test computes the hash as it goes, so it leaks
570        // two strings into a process that is about to end.
571        let pinned = rucc_sysroot::Pinned {
572            tuple: "x86_64-linux-musl",
573            url: "https://example.invalid/rucc-sysroot-x86_64-linux-musl.tar.gz",
574            sha256: String::leak(hash),
575        };
576        // Where a downloader would have written it, which is what the fetch looks at first.
577        let at = pinned.archive_in(&cache);
578        std::fs::create_dir_all(at.parent().expect("a parent")).expect("a downloads directory");
579        std::fs::copy(&built, &at).expect("the artifact should be placeable");
580
581        // And the kernel tree, which a Linux target is fetched with, placed the same way.
582        let kernel_manifest = kernel_manifest_for(KERNEL_FILES);
583        let (built, hash) = artifact_with(&tree, KERNEL_FILES, &kernel_manifest.render());
584        let kernel = rucc_sysroot::Pinned {
585            tuple: "kernel-headers",
586            url: "https://example.invalid/rucc-kernel-headers.tar.gz",
587            sha256: String::leak(hash),
588        };
589        let at = kernel.archive_in(&cache);
590        std::fs::create_dir_all(at.parent().expect("a parent")).expect("a downloads directory");
591        std::fs::copy(&built, &at).expect("the artifact should be placeable");
592
593        assert_eq!(crate::fetch_sysroot(&pinned, Some(&kernel), target(), &cache), 0);
594        let root = cache.join("sysroots").join("x86_64-linux-musl");
595        assert!(root.join("include/stdio.h").is_file());
596        assert_eq!(
597            std::fs::read_to_string(root.join("manifest")).expect("a manifest"),
598            manifest.render()
599        );
600        assert!(cache.join("kernel-headers/x86/asm/unistd.h").is_file());
601        // And again, which is the ordinary second run: the archives are still there, they still
602        // match, and the trees they would install are the trees that are already installed.
603        assert_eq!(crate::fetch_sysroot(&pinned, Some(&kernel), target(), &cache), 0);
604        // A target with no kernel tree is one artifact, and the fetch does not go looking for one.
605        assert_eq!(crate::fetch_sysroot(&pinned, None, target(), &cache), 0);
606    }
607
608    #[test]
609    fn the_same_artifact_twice_does_not_move_anything() {
610        let tree = Tree::new("again");
611        let manifest = manifest_for(FILES);
612        let (archive, hash) = artifact(&tree, FILES, &manifest);
613        let cache = tree.0.join("cache");
614
615        let first = install(&archive, &hash, target(), &cache).expect("the first install");
616        let second = install(&archive, &hash, target(), &cache).expect("the second install");
617        assert_eq!(second.before, Before::TheSame);
618        assert_eq!(second.root, first.root);
619        assert_eq!(second.digest, first.digest);
620    }
621
622    #[test]
623    fn a_hash_that_does_not_match_is_refused_before_anything_is_unpacked() {
624        let tree = Tree::new("hash");
625        let manifest = manifest_for(FILES);
626        let (archive, _) = artifact(&tree, FILES, &manifest);
627        let cache = tree.0.join("cache");
628
629        let wrong = "0".repeat(64);
630        let why =
631            install(&archive, &wrong, target(), &cache).expect_err("this is not the artifact");
632        assert!(why.message.contains("where this release pins"), "{}", why.message);
633        // Nothing was unpacked, which is the order section 13.8 asks for: the cache does not even
634        // have the directories in it.
635        assert!(!cache.exists(), "a refused artifact should not have reached the cache");
636    }
637
638    #[test]
639    fn an_artifact_for_another_target_is_refused() {
640        let tree = Tree::new("target");
641        let mut manifest = Manifest::new("aarch64-linux-musl".parse().expect("a tuple"));
642        for (path, text) in FILES {
643            manifest.push(Input {
644                path: (*path).to_owned(),
645                source: "musl-1.2.5".to_owned(),
646                url: "https://musl.libc.org/releases/musl-1.2.5.tar.gz".to_owned(),
647                sha256: sha256::hex(text.as_bytes()),
648                licence: Licence::Mit,
649                provenance: Provenance::Bundled,
650            });
651        }
652        let (archive, hash) = artifact(&tree, FILES, &manifest);
653        let cache = tree.0.join("cache");
654
655        let why = install(&archive, &hash, target(), &cache).expect_err("the wrong target");
656        assert!(why.message.contains("aarch64-linux-musl"), "{}", why.message);
657        assert!(why.message.contains("x86_64-linux-musl"), "{}", why.message);
658        assert!(!cache.join("sysroots").exists(), "nothing should have been installed");
659    }
660
661    #[test]
662    fn an_archive_with_no_record_in_it_is_refused() {
663        let tree = Tree::new("bare");
664        let staged = tree.0.join("staged");
665        std::fs::create_dir_all(&staged).expect("a directory");
666        std::fs::write(staged.join("include.h"), "int x;\n").expect("a file");
667        let archive = tree.0.join("bare.tar.gz");
668        let status = Command::new("tar")
669            .arg("-czf")
670            .arg(&archive)
671            .arg("-C")
672            .arg(&staged)
673            .arg(".")
674            .status()
675            .expect("tar should run");
676        assert!(status.success());
677        let hash = sha256::hex(&std::fs::read(&archive).expect("readable"));
678        let cache = tree.0.join("cache");
679
680        let why = install(&archive, &hash, target(), &cache).expect_err("no manifest");
681        assert!(why.message.contains("has no manifest in it"), "{}", why.message);
682    }
683
684    #[test]
685    fn a_file_the_record_does_not_name_is_refused() {
686        // The direction that is easy to leave out. A digest is a claim about what is under a
687        // directory, so an unrecorded file makes it a claim about less than what is there.
688        let tree = Tree::new("extra");
689        let manifest = manifest_for(FILES);
690        let mut with_extra: Vec<(&str, &str)> = FILES.to_vec();
691        with_extra.push(("lib/surprise.o", "nobody wrote this down\n"));
692        let (archive, hash) = artifact(&tree, &with_extra, &manifest);
693        let cache = tree.0.join("cache");
694
695        let why = install(&archive, &hash, target(), &cache).expect_err("an unrecorded file");
696        assert!(why.message.contains("lib/surprise.o"), "{}", why.message);
697        assert!(why.message.contains("not in the record"), "{}", why.message);
698    }
699
700    #[test]
701    fn a_file_whose_bytes_changed_is_refused_and_so_is_one_that_is_missing() {
702        let tree = Tree::new("bytes");
703        // The manifest describes what the files were supposed to be and the archive holds something
704        // else, which is what a producer with a bug in it looks like from here.
705        let manifest = manifest_for(&[("include/stdio.h", "what the record says\n")]);
706        let (archive, hash) = artifact(&tree, &[("include/stdio.h", "what is there\n")], &manifest);
707        let cache = tree.0.join("cache");
708        let why = install(&archive, &hash, target(), &cache).expect_err("changed bytes");
709        assert!(why.message.contains("include/stdio.h has sha256"), "{}", why.message);
710        assert!(why.message.contains("where the record says"), "{}", why.message);
711
712        let gone = Tree::new("gone");
713        let manifest = manifest_for(FILES);
714        let (archive, hash) = artifact(&gone, &FILES[..1], &manifest);
715        let cache = gone.0.join("cache");
716        let why = install(&archive, &hash, target(), &cache).expect_err("a missing file");
717        assert!(why.message.contains("lib/libc.so"), "{}", why.message);
718        assert!(why.message.contains("not in the archive"), "{}", why.message);
719    }
720
721    #[test]
722    fn more_than_one_disagreement_says_how_many() {
723        // Which of the two failures this is shows in the count, so the count is in the message.
724        let tree = Tree::new("count");
725        let manifest = manifest_for(&[("a.h", "one\n"), ("b.h", "two\n"), ("c.h", "three\n")]);
726        let (archive, hash) = artifact(
727            &tree,
728            &[("a.h", "not one\n"), ("b.h", "not two\n"), ("c.h", "three\n")],
729            &manifest,
730        );
731        let cache = tree.0.join("cache");
732
733        let why = install(&archive, &hash, target(), &cache).expect_err("two files disagree");
734        assert!(why.message.contains("and 1 more files disagree"), "{}", why.message);
735    }
736
737    #[test]
738    fn an_install_over_a_different_sysroot_says_what_it_replaced() {
739        let tree = Tree::new("replace");
740        let cache = tree.0.join("cache");
741        let first = manifest_for(&[("include/stdio.h", "the old one\n")]);
742        let (archive, hash) = artifact(&tree, &[("include/stdio.h", "the old one\n")], &first);
743        let done = install(&archive, &hash, target(), &cache).expect("the first install");
744        let was = done.digest.clone();
745
746        let second = Tree::new("replace-second");
747        let manifest = manifest_for(&[("include/stdio.h", "the new one\n")]);
748        let (archive, hash) = artifact(&second, &[("include/stdio.h", "the new one\n")], &manifest);
749        let done = install(&archive, &hash, target(), &cache).expect("the second install");
750
751        assert_eq!(done.before, Before::Different(was));
752        assert_eq!(
753            std::fs::read_to_string(done.root.join("include/stdio.h")).expect("the new file"),
754            "the new one\n"
755        );
756        // And the tree that was moved aside is gone rather than left beside the one that replaced
757        // it, since a cache that keeps every version it ever had is a cache nobody can size.
758        let kept: Vec<String> = std::fs::read_dir(cache.join("sysroots"))
759            .expect("the sysroots directory")
760            .map(|entry| entry.expect("an entry").file_name().to_string_lossy().into_owned())
761            .collect();
762        assert_eq!(kept, vec!["x86_64-linux-musl".to_owned()]);
763    }
764
765    /// The kernel tree's record for these files, which is four fields a line and no target.
766    fn kernel_manifest_for(files: &[(&str, &str)]) -> KernelManifest {
767        let mut manifest = KernelManifest::new(Version::new(6, 19));
768        for (path, text) in files {
769            manifest.push(KernelFile {
770                path: (*path).to_owned(),
771                source: "linux-6.19".to_owned(),
772                sha256: sha256::hex(text.as_bytes()),
773                licence: Licence::LinuxUapi,
774            });
775        }
776        manifest
777    }
778
779    const KERNEL_FILES: &[(&str, &str)] = &[
780        ("generic/linux/types.h", "#define _LINUX_TYPES_H\n"),
781        ("x86/asm/unistd.h", "#define __NR_read 0\n"),
782    ];
783
784    #[test]
785    fn the_kernel_tree_is_installed_beside_the_sysroots_and_not_under_them() {
786        let tree = Tree::new("kernel");
787        let manifest = kernel_manifest_for(KERNEL_FILES);
788        let (archive, hash) = artifact_with(&tree, KERNEL_FILES, &manifest.render());
789        let cache = tree.0.join("cache");
790
791        let done = install_kernel(&archive, &hash, &cache).expect("this one should install");
792        assert_eq!(done.root, cache.join("kernel-headers"));
793        assert_eq!(done.files, 2);
794        assert_eq!(done.digest, manifest.digest());
795        assert_eq!(done.before, Before::Nothing);
796        // Where `rucc_sysroot::Kernel` looks for the two directories a Linux compile searches.
797        let x86 = rucc_sysroot::Kernel::for_target(&cache, target()).expect("a Linux target");
798        assert!(x86.arch_include().join("asm/unistd.h").is_file());
799        assert!(x86.generic_include().join("linux/types.h").is_file());
800
801        let again = install_kernel(&archive, &hash, &cache).expect("the second install");
802        assert_eq!(again.before, Before::TheSame);
803    }
804
805    #[test]
806    fn a_sysroot_is_not_a_kernel_tree_and_a_kernel_tree_is_not_a_sysroot() {
807        // The two archives look alike from outside, a manifest and some directories, and each
808        // install reads only its own record, so handing one to the other is refused by the header
809        // before any file is looked at.
810        let tree = Tree::new("crossed");
811        let sysroot = manifest_for(FILES);
812        let (archive, hash) = artifact(&tree, FILES, &sysroot);
813        let cache = tree.0.join("cache");
814        let why = install_kernel(&archive, &hash, &cache).expect_err("a sysroot");
815        assert!(why.message.contains("kernel tree's record"), "{}", why.message);
816        assert!(!cache.join("kernel-headers").exists());
817
818        let other = Tree::new("crossed-kernel");
819        let kernel = kernel_manifest_for(KERNEL_FILES);
820        let (archive, hash) = artifact_with(&other, KERNEL_FILES, &kernel.render());
821        let cache = other.0.join("cache");
822        install(&archive, &hash, target(), &cache).expect_err("a kernel tree");
823        assert!(!cache.join("sysroots").exists());
824    }
825
826    #[test]
827    fn a_kernel_tree_with_a_file_its_record_does_not_name_is_refused() {
828        let tree = Tree::new("kernel-extra");
829        let manifest = kernel_manifest_for(KERNEL_FILES);
830        let mut with_extra: Vec<(&str, &str)> = KERNEL_FILES.to_vec();
831        with_extra.push(("arm64/asm/surprise.h", "nobody wrote this down\n"));
832        let (archive, hash) = artifact_with(&tree, &with_extra, &manifest.render());
833        let cache = tree.0.join("cache");
834        let why = install_kernel(&archive, &hash, &cache).expect_err("an unrecorded file");
835        assert!(why.message.contains("arm64/asm/surprise.h"), "{}", why.message);
836    }
837
838    #[test]
839    fn a_record_that_names_a_path_outside_the_tree_is_refused() {
840        // Not a likely producer bug, and the check is here because a manifest is data that has not
841        // been checked yet at the moment its paths are read.
842        assert!(relative(Path::new("/cache/sysroots/t"), "include/stdio.h").is_ok());
843        for path in ["../outside.h", "/etc/passwd", "include/../../outside.h"] {
844            let why = relative(Path::new("/cache/sysroots/t"), path)
845                .expect_err("this is not a path inside a sysroot");
846            assert!(why.contains(path), "{why}");
847        }
848    }
849
850    #[test]
851    fn the_walk_names_files_the_way_a_manifest_does() {
852        // With `/` between the parts whatever the host separator is, because the comparison is
853        // against a manifest and a manifest has one spelling.
854        let tree = Tree::new("walk");
855        tree.write("include/sys/types.h", "typedef int t;\n");
856        tree.write("manifest", "rucc sysroot manifest 3\n");
857        let mut found = Vec::new();
858        walk(&tree.0, String::new(), &mut found).expect("the walk should work");
859        found.sort();
860        assert_eq!(found, vec!["include/sys/types.h".to_owned(), "manifest".to_owned()]);
861    }
862
863    #[test]
864    fn verify_is_the_hash_of_the_file_and_says_both_when_it_is_not() {
865        let tree = Tree::new("verify");
866        tree.write("thing", "bytes\n");
867        let at = tree.0.join("thing");
868        let hash = sha256::hex(b"bytes\n");
869        assert!(verify(&at, &hash).is_ok());
870        let why = verify(&at, &"f".repeat(64)).expect_err("a mismatch");
871        assert!(why.message.contains(&hash), "{}", why.message);
872        assert!(why.message.contains(&"f".repeat(64)), "{}", why.message);
873
874        // A file that is not there is not a mismatch and does not read as one.
875        let why = verify(&tree.0.join("absent"), &hash).expect_err("nothing to hash");
876        assert!(!why.message.contains("where this release pins"), "{}", why.message);
877    }
878
879    #[test]
880    fn the_check_passes_a_tree_that_matches() {
881        // The unit underneath the install, so that a failure in the install tells you which half.
882        let tree = Tree::new("check");
883        for (path, text) in FILES {
884            tree.write(path, text);
885        }
886        tree.write("manifest", "rucc sysroot manifest 3\n");
887        let manifest = manifest_for(FILES);
888        let recorded: Vec<(&str, &str)> =
889            manifest.inputs().iter().map(|i| (i.path.as_str(), i.sha256.as_str())).collect();
890        assert_eq!(check(&tree.0, &recorded), Ok(()));
891        // An empty directory is not a file and is not a disagreement, which is what a tree that
892        // went through `tar` on one host and not another looks like.
893        std::fs::create_dir_all(tree.0.join("lib/empty")).expect("a directory");
894        assert_eq!(check(&tree.0, &recorded), Ok(()));
895    }
896
897    #[test]
898    fn installed_says_where_and_what() {
899        // The type the caller reports from, asserted once so that a change to it is a change to a
900        // test rather than to a message nobody reads.
901        let made = Installed {
902            root: PathBuf::from("/cache/sysroots/x86_64-linux-musl"),
903            digest: "0".repeat(64),
904            files: 3,
905            before: Before::Nothing,
906        };
907        assert_eq!(made.files, 3);
908        assert_eq!(made.before, Before::Nothing);
909    }
910}