|
| 1 | +//! cargo-sbom precursor files for external tools to create SBOM files from. |
| 2 | +//! See [`build_sbom_graph`] for more. |
| 3 | +
|
| 4 | +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; |
| 5 | +use std::path::PathBuf; |
| 6 | + |
| 7 | +use cargo_util_schemas::core::PackageIdSpec; |
| 8 | +use itertools::Itertools; |
| 9 | +use serde::Serialize; |
| 10 | + |
| 11 | +use crate::core::TargetKind; |
| 12 | +use crate::util::interning::InternedString; |
| 13 | +use crate::util::Rustc; |
| 14 | +use crate::CargoResult; |
| 15 | + |
| 16 | +use super::{BuildOutput, CompileMode}; |
| 17 | +use super::{BuildRunner, Unit}; |
| 18 | + |
| 19 | +/// Typed version of a SBOM format version number. |
| 20 | +#[derive(Serialize, Copy, Clone, Debug, Ord, PartialOrd, Eq, PartialEq)] |
| 21 | +pub struct SbomFormatVersion(u32); |
| 22 | + |
| 23 | +#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Serialize)] |
| 24 | +#[serde(rename_all = "snake_case")] |
| 25 | +enum SbomDependencyType { |
| 26 | + /// A dependency linked to the artifact produced by this unit. |
| 27 | + Normal, |
| 28 | + /// A dependency needed to run the build for this unit (e.g. a build script or proc-macro). |
| 29 | + /// The dependency is not linked to the artifact produced by this unit. |
| 30 | + Build, |
| 31 | +} |
| 32 | + |
| 33 | +#[derive(Serialize, Copy, Clone, Debug, Ord, PartialOrd, Eq, PartialEq)] |
| 34 | +struct SbomIndex(usize); |
| 35 | + |
| 36 | +#[derive(Serialize, Clone, Debug)] |
| 37 | +#[serde(rename_all = "snake_case")] |
| 38 | +struct SbomDependency { |
| 39 | + index: SbomIndex, |
| 40 | + kind: SbomDependencyType, |
| 41 | +} |
| 42 | + |
| 43 | +#[derive(Serialize, Clone, Debug)] |
| 44 | +#[serde(rename_all = "snake_case")] |
| 45 | +struct SbomPackage { |
| 46 | + id: PackageIdSpec, |
| 47 | + features: Vec<String>, |
| 48 | + cfgs: Vec<String>, |
| 49 | + dependencies: Vec<SbomDependency>, |
| 50 | + kind: TargetKind, |
| 51 | +} |
| 52 | + |
| 53 | +impl SbomPackage { |
| 54 | + pub fn new(unit: &Unit, build_script_output: Option<&BuildOutput>) -> Self { |
| 55 | + let package_id = unit.pkg.package_id().to_spec(); |
| 56 | + let features = unit.features.iter().map(|f| f.to_string()).collect_vec(); |
| 57 | + let cfgs = build_script_output |
| 58 | + .map(|b| b.cfgs.clone()) |
| 59 | + .unwrap_or_default(); |
| 60 | + Self { |
| 61 | + id: package_id, |
| 62 | + features, |
| 63 | + cfgs, |
| 64 | + dependencies: Vec::new(), |
| 65 | + kind: unit.target.kind().clone(), |
| 66 | + } |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +#[derive(Serialize, Clone)] |
| 71 | +#[serde(rename_all = "snake_case")] |
| 72 | +struct SbomRustc { |
| 73 | + version: String, |
| 74 | + wrapper: Option<PathBuf>, |
| 75 | + workspace_wrapper: Option<PathBuf>, |
| 76 | + commit_hash: Option<String>, |
| 77 | + host: String, |
| 78 | + verbose_version: String, |
| 79 | +} |
| 80 | + |
| 81 | +impl From<&Rustc> for SbomRustc { |
| 82 | + fn from(rustc: &Rustc) -> Self { |
| 83 | + Self { |
| 84 | + version: rustc.version.to_string(), |
| 85 | + wrapper: rustc.wrapper.clone(), |
| 86 | + workspace_wrapper: rustc.workspace_wrapper.clone(), |
| 87 | + commit_hash: rustc.commit_hash.clone(), |
| 88 | + host: rustc.host.to_string(), |
| 89 | + verbose_version: rustc.verbose_version.clone(), |
| 90 | + } |
| 91 | + } |
| 92 | +} |
| 93 | + |
| 94 | +#[derive(Serialize)] |
| 95 | +#[serde(rename_all = "snake_case")] |
| 96 | +pub struct Sbom { |
| 97 | + version: SbomFormatVersion, |
| 98 | + root: SbomIndex, |
| 99 | + packages: Vec<SbomPackage>, |
| 100 | + rustc: SbomRustc, |
| 101 | + target: InternedString, |
| 102 | +} |
| 103 | + |
| 104 | +/// Build an [`Sbom`] for the given [`Unit`]. |
| 105 | +pub fn build_sbom(build_runner: &BuildRunner<'_, '_>, root: &Unit) -> CargoResult<Sbom> { |
| 106 | + let bcx = build_runner.bcx; |
| 107 | + let rustc: SbomRustc = bcx.rustc().into(); |
| 108 | + |
| 109 | + let mut packages = Vec::new(); |
| 110 | + let build_script_outputs = build_runner.build_script_outputs.lock().unwrap(); |
| 111 | + let sbom_graph = build_sbom_graph(build_runner, root); |
| 112 | + |
| 113 | + // Build set of indicies for each node in the graph for fast lookup. |
| 114 | + let indicies: HashMap<&Unit, SbomIndex> = sbom_graph |
| 115 | + .keys() |
| 116 | + .enumerate() |
| 117 | + .map(|(i, dep)| (*dep, SbomIndex(i))) |
| 118 | + .collect(); |
| 119 | + |
| 120 | + // Add a item to the packages list for each node in the graph. |
| 121 | + for (unit, edges) in sbom_graph { |
| 122 | + let build_script_output = build_runner |
| 123 | + .find_build_script_metadata(unit) |
| 124 | + .and_then(|meta| build_script_outputs.get(meta)); |
| 125 | + let mut package = SbomPackage::new(unit, build_script_output); |
| 126 | + for (dep, kind) in edges { |
| 127 | + package.dependencies.push(SbomDependency { |
| 128 | + index: indicies[dep], |
| 129 | + kind: kind, |
| 130 | + }); |
| 131 | + } |
| 132 | + packages.push(package); |
| 133 | + } |
| 134 | + let target = match root.kind { |
| 135 | + super::CompileKind::Host => build_runner.bcx.host_triple(), |
| 136 | + super::CompileKind::Target(target) => target.rustc_target(), |
| 137 | + }; |
| 138 | + Ok(Sbom { |
| 139 | + version: SbomFormatVersion(1), |
| 140 | + packages, |
| 141 | + root: indicies[root], |
| 142 | + rustc, |
| 143 | + target, |
| 144 | + }) |
| 145 | +} |
| 146 | + |
| 147 | +/// List all dependencies, including transitive ones. A dependency can also appear multiple times |
| 148 | +/// if it's using different settings, e.g. profile, features or crate versions. |
| 149 | +/// |
| 150 | +/// Returns a graph of dependencies. |
| 151 | +fn build_sbom_graph<'a>( |
| 152 | + build_runner: &'a BuildRunner<'_, '_>, |
| 153 | + root: &'a Unit, |
| 154 | +) -> BTreeMap<&'a Unit, BTreeSet<(&'a Unit, SbomDependencyType)>> { |
| 155 | + tracing::trace!("building sbom graph for {}", root.pkg.package_id()); |
| 156 | + |
| 157 | + let mut queue = Vec::new(); |
| 158 | + let mut sbom_graph: BTreeMap<&Unit, BTreeSet<(&Unit, SbomDependencyType)>> = BTreeMap::new(); |
| 159 | + let mut visited = HashSet::new(); |
| 160 | + |
| 161 | + // Search to collect all dependencies of the root unit. |
| 162 | + queue.push((root, root, false)); |
| 163 | + while let Some((node, parent, is_build_dep)) = queue.pop() { |
| 164 | + let dependencies = sbom_graph.entry(parent).or_default(); |
| 165 | + for dep in build_runner.unit_deps(node) { |
| 166 | + let dep = &dep.unit; |
| 167 | + let (next_parent, next_is_build_dep) = if dep.mode == CompileMode::RunCustomBuild |
| 168 | + { |
| 169 | + // Nodes in the SBOM graph for building/running build scripts are moved on to their parent as build dependencies. |
| 170 | + (parent, true) |
| 171 | + } else { |
| 172 | + // Proc-macros and build scripts are marked as build dependencies. |
| 173 | + let dep_type = match is_build_dep || dep.target.proc_macro() { |
| 174 | + false => SbomDependencyType::Normal, |
| 175 | + true => SbomDependencyType::Build, |
| 176 | + }; |
| 177 | + dependencies.insert((dep, dep_type)); |
| 178 | + tracing::trace!( |
| 179 | + "adding sbom edge {} -> {} ({:?})", |
| 180 | + parent.pkg.package_id(), |
| 181 | + dep.pkg.package_id(), |
| 182 | + dep_type, |
| 183 | + ); |
| 184 | + (dep, false) |
| 185 | + }; |
| 186 | + if visited.insert(dep) { |
| 187 | + queue.push((dep, next_parent, next_is_build_dep)); |
| 188 | + } |
| 189 | + } |
| 190 | + } |
| 191 | + sbom_graph |
| 192 | +} |
0 commit comments