hermit-run 0.5.0

Hermit: a deterministic Linux execution engine for reproducible runs, record and replay, and concurrency-race search.
Documentation
/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree.
 */

use std::fs;
use std::io;
use std::os::unix;
use std::path::Path;
use std::path::PathBuf;

use tempfile::TempDir;

/// Represents a temporary chroot environment. This shall only contain the files
/// necessary to reproduce an execution.
pub struct TempChroot {
    dir: TempDir,
}

impl TempChroot {
    /// Creates a temporary directory that the tracee will chroot to. It is here
    /// where we can copy files needed by the tracee.
    pub fn new_in(data_dir: &Path) -> io::Result<Self> {
        let dir = TempDir::new_in(data_dir)?;
        Ok(Self { dir })
    }

    /// Returns the path to the chroot directory.
    pub fn path(&self) -> &Path {
        self.dir.path()
    }

    /// Returns a path relative to the chroot directory.
    pub fn relpath(&self, path: &Path) -> PathBuf {
        self.path().join(path.strip_prefix("/").unwrap_or(path))
    }

    /// Create symlink a file path into the chroot directory. Any intermediate
    /// directory that the path has will also be created. `link` must be an
    /// absolute path.
    ///
    /// NOTE: original path must exist in chroot directory, otherwise this
    /// could create a dead sym link.
    pub fn symlink(&self, original: &Path, link: &Path) -> io::Result<()> {
        let link = self.relpath(link);

        if let Some(dir) = link.parent() {
            fs::create_dir_all(dir)?;
        }

        unix::fs::symlink(original, link)
    }

    /// Creates a directory in the chroot.
    pub fn create_dir_all(&self, path: &Path) -> io::Result<()> {
        fs::create_dir_all(self.relpath(path))
    }

    /// Deletes the chroot. The `Drop` impl will also take care of this, but
    /// calling this explicitly gives a chance to catch any errors.
    pub fn remove(self) -> io::Result<()> {
        self.dir.close()
    }
}