Skip to main content

pdb_bindgen_codegen/
execution.rs

1use crate::Builder;
2use std::collections::{BTreeMap, BTreeSet};
3use std::error::Error as StdError;
4use std::ffi::{OsStr, OsString};
5use std::fmt;
6use std::path::{Path, PathBuf};
7
8/// The category of a [`GenerateError`].
9#[derive(Clone, Copy, Debug, Eq, PartialEq)]
10#[non_exhaustive]
11pub enum GenerateErrorKind {
12    /// A required Cargo environment value was unavailable or not UTF-8.
13    Environment,
14    /// Cargo could not receive a rerun directive.
15    CargoDirective,
16    /// Source discovery failed.
17    Discovery,
18    /// PDB acquisition failed.
19    Acquisition,
20    /// PDB normalization failed.
21    Pdb,
22    /// Binding generation failed.
23    Codegen,
24    /// Generated output publication failed.
25    Output,
26}
27
28/// An error from [`Builder::generate`].
29#[derive(Debug)]
30pub struct GenerateError {
31    kind: GenerateErrorKind,
32    image: Option<String>,
33    source: Box<GenerateSource>,
34}
35
36#[derive(Debug)]
37enum GenerateSource {
38    Environment {
39        name: &'static str,
40        reason: &'static str,
41    },
42    CargoDirective(std::io::Error),
43    Discovery(crate::discovery::Diagnostic),
44    Acquisition(crate::acquisition::Error),
45    Pdb(crate::pdb::error::Error),
46    Codegen(crate::codegen::Error),
47    Output(crate::output::OutputError),
48}
49
50impl GenerateError {
51    /// Returns the failure category.
52    #[must_use]
53    pub const fn kind(&self) -> GenerateErrorKind {
54        self.kind
55    }
56
57    /// Returns the logical image being processed, when applicable.
58    #[must_use]
59    pub fn image(&self) -> Option<&str> {
60        self.image.as_deref()
61    }
62
63    fn environment(name: &'static str, reason: &'static str) -> Self {
64        Self {
65            kind: GenerateErrorKind::Environment,
66            image: None,
67            source: Box::new(GenerateSource::Environment { name, reason }),
68        }
69    }
70
71    fn with_image(kind: GenerateErrorKind, image: &str, source: GenerateSource) -> Self {
72        Self {
73            kind,
74            image: Some(image.to_owned()),
75            source: Box::new(source),
76        }
77    }
78
79    fn codegen(source: crate::codegen::Error) -> Self {
80        Self {
81            kind: GenerateErrorKind::Codegen,
82            image: source.image().map(str::to_owned),
83            source: Box::new(GenerateSource::Codegen(source)),
84        }
85    }
86}
87
88impl fmt::Display for GenerateError {
89    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90        match &*self.source {
91            GenerateSource::Environment { name, reason } => {
92                write!(f, "Cargo environment {name} {reason}")
93            }
94            GenerateSource::CargoDirective(_) => f.write_str("cannot write Cargo rerun directive"),
95            GenerateSource::Discovery(source) => write!(f, "source discovery failed: {source}"),
96            GenerateSource::Acquisition(source) => write!(
97                f,
98                "PDB acquisition failed for image {}: {source}",
99                self.image
100                    .as_deref()
101                    .expect("acquisition errors have an image")
102            ),
103            GenerateSource::Pdb(source) => write!(
104                f,
105                "PDB normalization failed for image {}: {source}",
106                self.image.as_deref().expect("PDB errors have an image")
107            ),
108            GenerateSource::Codegen(source) => write!(f, "binding generation failed: {source}"),
109            GenerateSource::Output(source) => {
110                write!(f, "generated output publication failed: {source}")
111            }
112        }
113    }
114}
115
116impl StdError for GenerateError {
117    fn source(&self) -> Option<&(dyn StdError + 'static)> {
118        match &*self.source {
119            GenerateSource::Environment { .. } => None,
120            GenerateSource::CargoDirective(source) => Some(source),
121            GenerateSource::Discovery(source) => Some(source),
122            GenerateSource::Acquisition(source) => Some(source),
123            GenerateSource::Pdb(source) => Some(source),
124            GenerateSource::Codegen(source) => Some(source),
125            GenerateSource::Output(source) => Some(source),
126        }
127    }
128}
129
130impl Builder {
131    /// Discovers active markers, acquires their PDBs, and publishes generated bindings.
132    ///
133    /// This is intended for a Cargo build script. It reads `CARGO_MANIFEST_DIR` and
134    /// `OUT_DIR`, emits the required Cargo rerun directives, and publishes only after
135    /// all active PDBs have been normalized and rendered.
136    ///
137    /// # Errors
138    ///
139    /// Returns a [`GenerateError`] when required Cargo environment is unavailable or
140    /// when source discovery, PDB acquisition or normalization, binding generation,
141    /// Cargo directive emission, or output publication fails. Use
142    /// [`GenerateError::kind`] and [`GenerateError::image`] for structured context.
143    pub fn generate(&self) -> Result<(), GenerateError> {
144        let environment = std::env::vars_os().collect::<BTreeMap<_, _>>();
145        let package = required_path(&environment, "CARGO_MANIFEST_DIR")?;
146        let out_dir = required_path(&environment, "OUT_DIR")?;
147        let builder = self.resolve_paths(&package);
148        let roots = effective_roots(&package, &builder);
149        let discovery_environment = environment.into_iter().collect::<Vec<_>>();
150
151        let discovery =
152            crate::discovery::discover(&package, &builder, discovery_environment.clone()).map_err(
153                |source| GenerateError {
154                    kind: GenerateErrorKind::Discovery,
155                    image: None,
156                    source: Box::new(GenerateSource::Discovery(source)),
157                },
158            )?;
159        let images = discovery
160            .resolved
161            .iter()
162            .map(|item| item.image.image.clone())
163            .collect::<BTreeSet<_>>();
164
165        let mut directives = BTreeSet::new();
166        directives.insert(package.join("Cargo.toml"));
167        directives.extend(roots);
168        for image in &images {
169            let configured = builder
170                .images()
171                .iter()
172                .find(|candidate| candidate.key() == image)
173                .expect("discovery validates image keys");
174            if let Some(path) = configured.local_pdb_path() {
175                directives.insert(path.to_path_buf());
176            }
177        }
178        emit_directives(directives, &discovery_environment)?;
179
180        let mut databases = BTreeMap::new();
181        for image in images {
182            let configured = builder
183                .images()
184                .iter()
185                .find(|candidate| candidate.key() == image)
186                .expect("discovery validates image keys");
187            let acquired =
188                crate::acquisition::acquire(&builder, configured, &out_dir).map_err(|source| {
189                    GenerateError::with_image(
190                        GenerateErrorKind::Acquisition,
191                        &image,
192                        GenerateSource::Acquisition(source),
193                    )
194                })?;
195            let database = crate::pdb::read(&acquired.path).map_err(|source| {
196                GenerateError::with_image(
197                    GenerateErrorKind::Pdb,
198                    &image,
199                    GenerateSource::Pdb(source),
200                )
201            })?;
202            databases.insert(image, database);
203        }
204        let generated = crate::codegen::generate(&discovery.resolved, &databases)
205            .map_err(GenerateError::codegen)?;
206        generated.publish(&out_dir).map_err(|source| GenerateError {
207            kind: GenerateErrorKind::Output,
208            image: None,
209            source: Box::new(GenerateSource::Output(source)),
210        })
211    }
212}
213
214fn required_path(
215    environment: &BTreeMap<OsString, OsString>,
216    name: &'static str,
217) -> Result<PathBuf, GenerateError> {
218    let value = environment
219        .get(OsStr::new(name))
220        .ok_or_else(|| GenerateError::environment(name, "is missing"))?;
221    let value = value
222        .to_str()
223        .ok_or_else(|| GenerateError::environment(name, "is not UTF-8"))?;
224    Ok(PathBuf::from(value))
225}
226
227fn effective_roots(package: &Path, builder: &Builder) -> BTreeSet<PathBuf> {
228    let roots = builder
229        .source_roots()
230        .map(Path::to_path_buf)
231        .collect::<Vec<_>>();
232    if roots.is_empty() {
233        [package.join("src")].into_iter().collect()
234    } else {
235        roots.into_iter().map(|root| package.join(root)).collect()
236    }
237}
238
239fn emit_directives(
240    paths: BTreeSet<PathBuf>,
241    environment: &[(OsString, OsString)],
242) -> Result<(), GenerateError> {
243    let mut output = std::io::stdout().lock();
244    emit_directives_to(&mut output, paths, environment)
245}
246
247fn emit_directives_to(
248    output: &mut impl std::io::Write,
249    paths: BTreeSet<PathBuf>,
250    environment: &[(OsString, OsString)],
251) -> Result<(), GenerateError> {
252    for path in paths {
253        directive(output, "cargo::rerun-if-changed", &path)?;
254    }
255    let names = environment
256        .iter()
257        .filter_map(|(name, _)| name.to_str())
258        .filter(|name| name.starts_with("CARGO_CFG_") || name.starts_with("CARGO_FEATURE_"))
259        .collect::<BTreeSet<_>>();
260    for name in names {
261        directive(output, "cargo::rerun-if-env-changed", Path::new(name))?;
262    }
263    Ok(())
264}
265
266fn directive(
267    output: &mut impl std::io::Write,
268    prefix: &str,
269    value: &Path,
270) -> Result<(), GenerateError> {
271    let value = value.to_str().ok_or_else(|| GenerateError {
272        kind: GenerateErrorKind::CargoDirective,
273        image: None,
274        source: Box::new(GenerateSource::CargoDirective(std::io::Error::new(
275            std::io::ErrorKind::InvalidData,
276            "Cargo directive text is not UTF-8",
277        ))),
278    })?;
279    writeln!(output, "{prefix}={value}").map_err(|source| GenerateError {
280        kind: GenerateErrorKind::CargoDirective,
281        image: None,
282        source: Box::new(GenerateSource::CargoDirective(source)),
283    })
284}
285
286#[cfg(test)]
287mod tests {
288    use super::*;
289
290    #[test]
291    fn missing_required_environment_is_typed() {
292        let error = required_path(&BTreeMap::new(), "OUT_DIR").unwrap_err();
293        assert_eq!(error.kind(), GenerateErrorKind::Environment);
294        assert_eq!(error.image(), None);
295        assert!(error.to_string().contains("OUT_DIR is missing"));
296    }
297
298    #[cfg(unix)]
299    #[test]
300    fn non_utf8_environment_is_typed() {
301        use std::os::unix::ffi::OsStringExt as _;
302        let mut environment = BTreeMap::new();
303        environment.insert(OsString::from("OUT_DIR"), OsString::from_vec(vec![0xff]));
304        let error = required_path(&environment, "OUT_DIR").unwrap_err();
305        assert_eq!(error.kind(), GenerateErrorKind::Environment);
306        assert!(error.to_string().contains("not UTF-8"));
307    }
308
309    #[test]
310    fn directives_are_sorted_and_deduplicated() {
311        let paths = [PathBuf::from("z"), PathBuf::from("a"), PathBuf::from("a")]
312            .into_iter()
313            .collect();
314        let environment = vec![
315            (OsString::from("CARGO_FEATURE_Z"), OsString::new()),
316            (OsString::from("IGNORED"), OsString::new()),
317            (OsString::from("CARGO_CFG_A"), OsString::new()),
318            (OsString::from("CARGO_CFG_A"), OsString::new()),
319        ];
320        let mut output = Vec::new();
321        emit_directives_to(&mut output, paths, &environment).unwrap();
322        assert_eq!(
323            String::from_utf8(output).unwrap(),
324            "cargo::rerun-if-changed=a\ncargo::rerun-if-changed=z\ncargo::rerun-if-env-changed=CARGO_CFG_A\ncargo::rerun-if-env-changed=CARGO_FEATURE_Z\n"
325        );
326    }
327
328    #[test]
329    fn writer_failure_is_a_cargo_directive_error() {
330        struct Broken;
331        impl std::io::Write for Broken {
332            fn write(&mut self, _: &[u8]) -> std::io::Result<usize> {
333                Err(std::io::Error::other("broken"))
334            }
335            fn flush(&mut self) -> std::io::Result<()> {
336                Ok(())
337            }
338        }
339        let error =
340            emit_directives_to(&mut Broken, [PathBuf::from("a")].into_iter().collect(), &[])
341                .unwrap_err();
342        assert_eq!(error.kind(), GenerateErrorKind::CargoDirective);
343        assert!(error.source().is_some());
344    }
345
346    #[cfg(unix)]
347    #[test]
348    fn non_utf8_directive_is_a_cargo_directive_error() {
349        use std::os::unix::ffi::OsStringExt as _;
350
351        let error = emit_directives_to(
352            &mut Vec::new(),
353            [PathBuf::from(OsString::from_vec(vec![0xff]))]
354                .into_iter()
355                .collect(),
356            &[],
357        )
358        .unwrap_err();
359        assert_eq!(error.kind(), GenerateErrorKind::CargoDirective);
360        assert!(error.source().is_some());
361    }
362
363    #[test]
364    fn image_context_is_displayed_and_inspectable() {
365        let error = GenerateError::with_image(
366            GenerateErrorKind::Pdb,
367            "primary",
368            GenerateSource::Pdb(crate::pdb::error::Error::Parse {
369                operation: "read",
370                detail: "bad".into(),
371            }),
372        );
373        assert_eq!(error.image(), Some("primary"));
374        assert!(error.to_string().contains("image primary"));
375        assert!(error.source().is_some());
376    }
377
378    #[test]
379    fn codegen_errors_preserve_item_image_and_source_chain() {
380        let error = GenerateError::codegen(crate::codegen::Error::context(
381            "primary".into(),
382            crate::codegen::Error::KindMismatch {
383                pdb_name: "R".into(),
384                expected: "struct",
385                actual: "union",
386            },
387        ));
388        assert_eq!(error.kind(), GenerateErrorKind::Codegen);
389        assert_eq!(error.image(), Some("primary"));
390        let source = error.source().expect("codegen source");
391        assert!(source.source().is_some());
392    }
393}