rust-bindgen icon indicating copy to clipboard operation
rust-bindgen copied to clipboard

Input validation: missing header(s) causes panic

Open mtb0x1 opened this issue 1 month ago • 0 comments

Context : During compile time, I was facing a panic with generic error message for the code below


println!("cargo:rerun-if-changed=src/xyz.h");

bindgen::Builder::default()
    .layout_tests(false)
    .allowlist_function("xyz_.*")
    .generate()
    .expect("Unable to generate bindings")
    .write_to_file("src/xyz.rs")
    .expect("Couldn't write bindings!");


error: failed to run custom build command for `somecrate v0.3.0 (D:\SomeCrate)`

Caused by:
  process didn't exit successfully: `D:\SomeCrate\target\debug\build\somecrate-a18697f15db8ca68\build-script-build` (exit code: 101)
  --- stderr

  thread 'main' (17540) panicked at C:\Users\userZ\.cargo\registry\src\index.crates.io-1949cf8c6b5b557f\bindgen-0.72.1\ir\context.rs:562:15:
  libclang error; possible causes include:
  - Invalid flag syntax
  - Unrecognized flags
  - Invalid flag arguments
  - File I/O errors
  - Host vs. target architecture mismatch
  If you encounter an error missing from this list, please file an issue or a PR!
  stack backtrace:
     0:     0x7ff750f178c2 - std::backtrace_rs::backtrace::win64::trace
                                 at /rustc/ed61e7d7e242494fb7057f2657300d9e77bb4fcb/library\std\src\..\..\backtrace\src\backtrace\win64.rs:85
     1:     0x7ff750f178c2 - std::backtrace_rs::backtrace::trace_unsynchronized
                                 at /rustc/ed61e7d7e242494fb7057f2657300d9e77bb4fcb/library\std\src\..\..\backtrace\src\backtrace\mod.rs:66
...

This sent me trough the rabbit whole of trying to figure out the root cause. (spoil : I forgot to provide header(s) file/content)

After few minutes and few checks, someone on discord pointed out that this might be related to clang version and it might be better with a newer version. I checked but same result.

I even went as far as switching to clang_parseTranslationUnit2, which gave me a CXError_ASTReadError, this means (I guess) there is no possible way to recover since clang can't emit diagnostic if the AST step fails.

At least for this specific case (missing headers), we can sanitize the input and avoid headaches for futures use cases.

N.B : the case where header file is provided but doesn't exist on file system, is already handled (Unable to generate bindings: NotExist("xyz.c"))

mtb0x1 avatar Nov 18 '25 14:11 mtb0x1