Debian Codegraph @

.cargo/vendor/bindgen/lib.rs

raw
1 //! Generate Rust bindings for C and C++ libraries.
2 //!
3 //! Provide a C/C++ header file, receive Rust FFI code to call into C/C++
4 //! functions and use types defined in the header.
5 //!
6 //! See the [`Builder`](./struct.Builder.html) struct for usage.
7 //!
8 //! See the [Users Guide](https://rust-lang.github.io/rust-bindgen/) for
9 //! additional documentation.
10 #![deny(missing_docs)]
11 #![deny(unused_extern_crates)]
12 #![deny(clippy::disallowed_methods)]
13 // To avoid rather annoying warnings when matching with CXCursor_xxx as a
14 // constant.
15 #![allow(non_upper_case_globals)]
16 // `quote!` nests quite deeply.
17 #![recursion_limit = "128"]
18
19 #[macro_use]
20 extern crate bitflags;
21 #[macro_use]
22 extern crate lazy_static;
23 #[macro_use]
24 extern crate quote;
25
26 #[cfg(feature = "logging")]
27 #[macro_use]
28 extern crate log;
29
30 #[cfg(not(feature = "logging"))]
31 #[macro_use]
32 mod log_stubs;
33
34 #[macro_use]
35 mod extra_assertions;
36
37 mod codegen;
38 mod deps;
39 mod options;
40 mod time;
41
42 pub mod callbacks;
43
44 mod clang;
45 #[cfg(feature = "experimental")]
46 mod diagnostics;
47 mod features;
48 mod ir;
49 mod parse;
50 mod regex_set;
51
52 pub use codegen::{
53 AliasVariation, EnumVariation, MacroTypeVariation, NonCopyUnionStyle,
54 };
55 pub use features::{RustTarget, LATEST_STABLE_RUST, RUST_TARGET_STRINGS};
56 pub use ir::annotations::FieldVisibilityKind;
57 pub use ir::function::Abi;
58 pub use regex_set::RegexSet;
59
60 use codegen::CodegenError;
61 use features::RustFeatures;
62 use ir::comment;
63 use ir::context::{BindgenContext, ItemId};
64 use ir::item::Item;
65 use options::BindgenOptions;
66 use parse::ParseError;
67
68 use std::borrow::Cow;
69 use std::collections::hash_map::Entry;
70 use std::env;
71 use std::ffi::OsStr;
72 use std::fs::{File, OpenOptions};
73 use std::io::{self, Write};
74 use std::path::{Path, PathBuf};
75 use std::process::{Command, Stdio};
76 use std::rc::Rc;
77 use std::str::FromStr;
78
79 // Some convenient typedefs for a fast hash map and hash set.
80 type HashMap<K, V> = rustc_hash::FxHashMap<K, V>;
81 type HashSet<K> = rustc_hash::FxHashSet<K>;
82
83 /// Default prefix for the anon fields.
84 pub const DEFAULT_ANON_FIELDS_PREFIX: &str = "__bindgen_anon_";
85
86 const DEFAULT_NON_EXTERN_FNS_SUFFIX: &str = "__extern";
87
88 fn file_is_cpp(name_file: &str) -> bool {
89 name_file.ends_with(".hpp") ||
90 name_file.ends_with(".hxx") ||
91 name_file.ends_with(".hh") ||
92 name_file.ends_with(".h++")
93 }
94
95 fn args_are_cpp(clang_args: &[String]) -> bool {
96 for w in clang_args.windows(2) {
97 if w[0] == "-xc++" || w[1] == "-xc++" {
98 return true;
99 }
100 if w[0] == "-x" && w[1] == "c++" {
101 return true;
102 }
103 if w[0] == "-include" && file_is_cpp(&w[1]) {
104 return true;
105 }
106 }
107 false
108 }
109
110 bitflags! {
111 /// A type used to indicate which kind of items we have to generate.
112 pub struct CodegenConfig: u32 {
113 /// Whether to generate functions.
114 const FUNCTIONS = 1 << 0;
115 /// Whether to generate types.
116 const TYPES = 1 << 1;
117 /// Whether to generate constants.
118 const VARS = 1 << 2;
119 /// Whether to generate methods.
120 const METHODS = 1 << 3;
121 /// Whether to generate constructors
122 const CONSTRUCTORS = 1 << 4;
123 /// Whether to generate destructors.
124 const DESTRUCTORS = 1 << 5;
125 }
126 }
127
128 impl CodegenConfig {
129 /// Returns true if functions should be generated.
130 pub fn functions(self) -> bool {
131 self.contains(CodegenConfig::FUNCTIONS)
132 }
133
134 /// Returns true if types should be generated.
135 pub fn types(self) -> bool {
136 self.contains(CodegenConfig::TYPES)
137 }
138
139 /// Returns true if constants should be generated.
140 pub fn vars(self) -> bool {
141 self.contains(CodegenConfig::VARS)
142 }
143
144 /// Returns true if methds should be generated.
145 pub fn methods(self) -> bool {
146 self.contains(CodegenConfig::METHODS)
147 }
148
149 /// Returns true if constructors should be generated.
150 pub fn constructors(self) -> bool {
151 self.contains(CodegenConfig::CONSTRUCTORS)
152 }
153
154 /// Returns true if destructors should be generated.
155 pub fn destructors(self) -> bool {
156 self.contains(CodegenConfig::DESTRUCTORS)
157 }
158 }
159
160 impl Default for CodegenConfig {
161 fn default() -> Self {
162 CodegenConfig::all()
163 }
164 }
165
166 /// Formatting tools that can be used to format the bindings
167 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
168 #[non_exhaustive]
169 pub enum Formatter {
170 /// Do not format the bindings.
171 None,
172 /// Use `rustfmt` to format the bindings.
173 Rustfmt,
174 #[cfg(feature = "prettyplease")]
175 /// Use `prettyplease` to format the bindings.
176 Prettyplease,
177 }
178
179 impl Default for Formatter {
180 fn default() -> Self {
181 Self::Rustfmt
182 }
183 }
184
185 impl FromStr for Formatter {
186 type Err = String;
187
188 fn from_str(s: &str) -> Result<Self, Self::Err> {
189 match s {
190 "none" => Ok(Self::None),
191 "rustfmt" => Ok(Self::Rustfmt),
192 #[cfg(feature = "prettyplease")]
193 "prettyplease" => Ok(Self::Prettyplease),
194 _ => Err(format!("`{}` is not a valid formatter", s)),
195 }
196 }
197 }
198
199 impl std::fmt::Display for Formatter {
200 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
201 let s = match self {
202 Self::None => "none",
203 Self::Rustfmt => "rustfmt",
204 #[cfg(feature = "prettyplease")]
205 Self::Prettyplease => "prettyplease",
206 };
207
208 s.fmt(f)
209 }
210 }
211
212 /// Configure and generate Rust bindings for a C/C++ header.
213 ///
214 /// This is the main entry point to the library.
215 ///
216 /// ```ignore
217 /// use bindgen::builder;
218 ///
219 /// // Configure and generate bindings.
220 /// let bindings = builder().header("path/to/input/header")
221 /// .allowlist_type("SomeCoolClass")
222 /// .allowlist_function("do_some_cool_thing")
223 /// .generate()?;
224 ///
225 /// // Write the generated bindings to an output file.
226 /// bindings.write_to_file("path/to/output.rs")?;
227 /// ```
228 ///
229 /// # Enums
230 ///
231 /// Bindgen can map C/C++ enums into Rust in different ways. The way bindgen maps enums depends on
232 /// the pattern passed to several methods:
233 ///
234 /// 1. [`constified_enum_module()`](#method.constified_enum_module)
235 /// 2. [`bitfield_enum()`](#method.bitfield_enum)
236 /// 3. [`newtype_enum()`](#method.newtype_enum)
237 /// 4. [`rustified_enum()`](#method.rustified_enum)
238 ///
239 /// For each C enum, bindgen tries to match the pattern in the following order:
240 ///
241 /// 1. Constified enum module
242 /// 2. Bitfield enum
243 /// 3. Newtype enum
244 /// 4. Rustified enum
245 ///
246 /// If none of the above patterns match, then bindgen will generate a set of Rust constants.
247 ///
248 /// # Clang arguments
249 ///
250 /// Extra arguments can be passed to with clang:
251 /// 1. [`clang_arg()`](#method.clang_arg): takes a single argument
252 /// 2. [`clang_args()`](#method.clang_args): takes an iterator of arguments
253 /// 3. `BINDGEN_EXTRA_CLANG_ARGS` environment variable: whitespace separate
254 /// environment variable of arguments
255 ///
256 /// Clang arguments specific to your crate should be added via the
257 /// `clang_arg()`/`clang_args()` methods.
258 ///
259 /// End-users of the crate may need to set the `BINDGEN_EXTRA_CLANG_ARGS` environment variable to
260 /// add additional arguments. For example, to build against a different sysroot a user could set
261 /// `BINDGEN_EXTRA_CLANG_ARGS` to `--sysroot=/path/to/sysroot`.
262 ///
263 /// # Regular expression arguments
264 ///
265 /// Some [`Builder`] methods such as the `allowlist_*` and `blocklist_*` methods allow regular
266 /// expressions as arguments. These regular expressions will be enclosed in parentheses and
267 /// anchored with `^` and `$`. So if the argument passed is `<regex>`, the regular expression to be
268 /// stored will be `^(<regex>)$`.
269 ///
270 /// As a consequence, regular expressions passed to `bindgen` will try to match the whole name of
271 /// an item instead of a section of it, which means that to match any items with the prefix
272 /// `prefix`, the `prefix.*` regular expression must be used.
273 ///
274 /// Certain methods, like [`Builder::allowlist_function`], use regular expressions over function
275 /// names. To match C++ methods, prefix the name of the type where they belong followed by an
276 /// underscore. So if the type `Foo` has a method `bar`, it can be matched with the `Foo_bar`
277 /// regular expression.
278 ///
279 /// Additionally, Objective-C interfaces can be matched by prefixing the regular expression with
280 /// `I`. For example, the `IFoo` regular expression matches the `Foo` interface and the `IFoo_foo`
281 /// regular expression matches the `foo` method of the `Foo` interface.
282 ///
283 /// Releases of `bindgen` with a version lesser or equal to `0.62.0` used to accept the wildcard
284 /// pattern `*` as a valid regular expression. This behavior has been deprecated and the `.*`
285 /// regular expression must be used instead.
286 #[derive(Debug, Default, Clone)]
287 pub struct Builder {
288 options: BindgenOptions,
289 }
290
291 /// Construct a new [`Builder`](./struct.Builder.html).
292 pub fn builder() -> Builder {
293 Default::default()
294 }
295
296 fn get_extra_clang_args(
297 parse_callbacks: &[Rc<dyn callbacks::ParseCallbacks>],
298 ) -> Vec<String> {
299 // Add any extra arguments from the environment to the clang command line.
300 let extra_clang_args = match get_target_dependent_env_var(
301 parse_callbacks,
302 "BINDGEN_EXTRA_CLANG_ARGS",
303 ) {
304 None => return vec![],
305 Some(s) => s,
306 };
307
308 // Try to parse it with shell quoting. If we fail, make it one single big argument.
309 if let Some(strings) = shlex::split(&extra_clang_args) {
310 return strings;
311 }
312 vec![extra_clang_args]
313 }
314
315 impl Builder {
316 /// Generate the Rust bindings using the options built up thus far.
317 pub fn generate(mut self) -> Result<Bindings, BindgenError> {
318 // Add any extra arguments from the environment to the clang command line.
319 self.options
320 .clang_args
321 .extend(get_extra_clang_args(&self.options.parse_callbacks));
322
323 // Transform input headers to arguments on the clang command line.
324 self.options.clang_args.extend(
325 self.options.input_headers
326 [..self.options.input_headers.len().saturating_sub(1)]
327 .iter()
328 .flat_map(|header| ["-include".into(), header.to_string()]),
329 );
330
331 let input_unsaved_files =
332 std::mem::take(&mut self.options.input_header_contents)
333 .into_iter()
334 .map(|(name, contents)| clang::UnsavedFile::new(name, contents))
335 .collect::<Vec<_>>();
336
337 Bindings::generate(self.options, input_unsaved_files)
338 }
339
340 /// Preprocess and dump the input header files to disk.
341 ///
342 /// This is useful when debugging bindgen, using C-Reduce, or when filing
343 /// issues. The resulting file will be named something like `__bindgen.i` or
344 /// `__bindgen.ii`
345 pub fn dump_preprocessed_input(&self) -> io::Result<()> {
346 let clang =
347 clang_sys::support::Clang::find(None, &[]).ok_or_else(|| {
348 io::Error::new(
349 io::ErrorKind::Other,
350 "Cannot find clang executable",
351 )
352 })?;
353
354 // The contents of a wrapper file that includes all the input header
355 // files.
356 let mut wrapper_contents = String::new();
357
358 // Whether we are working with C or C++ inputs.
359 let mut is_cpp = args_are_cpp(&self.options.clang_args);
360
361 // For each input header, add `#include "$header"`.
362 for header in &self.options.input_headers {
363 is_cpp |= file_is_cpp(header);
364
365 wrapper_contents.push_str("#include \"");
366 wrapper_contents.push_str(header);
367 wrapper_contents.push_str("\"\n");
368 }
369
370 // For each input header content, add a prefix line of `#line 0 "$name"`
371 // followed by the contents.
372 for (name, contents) in &self.options.input_header_contents {
373 is_cpp |= file_is_cpp(name);
374
375 wrapper_contents.push_str("#line 0 \"");
376 wrapper_contents.push_str(name);
377 wrapper_contents.push_str("\"\n");
378 wrapper_contents.push_str(contents);
379 }
380
381 let wrapper_path = PathBuf::from(if is_cpp {
382 "__bindgen.cpp"
383 } else {
384 "__bindgen.c"
385 });
386
387 {
388 let mut wrapper_file = File::create(&wrapper_path)?;
389 wrapper_file.write_all(wrapper_contents.as_bytes())?;
390 }
391
392 let mut cmd = Command::new(clang.path);
393 cmd.arg("-save-temps")
394 .arg("-E")
395 .arg("-C")
396 .arg("-c")
397 .arg(&wrapper_path)
398 .stdout(Stdio::piped());
399
400 for a in &self.options.clang_args {
401 cmd.arg(a);
402 }
403
404 for a in get_extra_clang_args(&self.options.parse_callbacks) {
405 cmd.arg(a);
406 }
407
408 let mut child = cmd.spawn()?;
409
410 let mut preprocessed = child.stdout.take().unwrap();
411 let mut file = File::create(if is_cpp {
412 "__bindgen.ii"
413 } else {
414 "__bindgen.i"
415 })?;
416 io::copy(&mut preprocessed, &mut file)?;
417
418 if child.wait()?.success() {
419 Ok(())
420 } else {
421 Err(io::Error::new(
422 io::ErrorKind::Other,
423 "clang exited with non-zero status",
424 ))
425 }
426 }
427 }
428
429 impl BindgenOptions {
430 fn build(&mut self) {
431 const REGEX_SETS_LEN: usize = 27;
432
433 let regex_sets: [_; REGEX_SETS_LEN] = [
434 &mut self.allowlisted_vars,
435 &mut self.allowlisted_types,
436 &mut self.allowlisted_functions,
437 &mut self.allowlisted_files,
438 &mut self.blocklisted_types,
439 &mut self.blocklisted_functions,
440 &mut self.blocklisted_items,
441 &mut self.blocklisted_files,
442 &mut self.opaque_types,
443 &mut self.bitfield_enums,
444 &mut self.constified_enums,
445 &mut self.constified_enum_modules,
446 &mut self.newtype_enums,
447 &mut self.newtype_global_enums,
448 &mut self.rustified_enums,
449 &mut self.rustified_non_exhaustive_enums,
450 &mut self.type_alias,
451 &mut self.new_type_alias,
452 &mut self.new_type_alias_deref,
453 &mut self.bindgen_wrapper_union,
454 &mut self.manually_drop_union,
455 &mut self.no_partialeq_types,
456 &mut self.no_copy_types,
457 &mut self.no_debug_types,
458 &mut self.no_default_types,
459 &mut self.no_hash_types,
460 &mut self.must_use_types,
461 ];
462
463 let record_matches = self.record_matches;
464 #[cfg(feature = "experimental")]
465 {
466 let sets_len = REGEX_SETS_LEN + self.abi_overrides.len();
467 let names = if self.emit_diagnostics {
468 <[&str; REGEX_SETS_LEN]>::into_iter([
469 "--blocklist-type",
470 "--blocklist-function",
471 "--blocklist-item",
472 "--blocklist-file",
473 "--opaque-type",
474 "--allowlist-type",
475 "--allowlist-function",
476 "--allowlist-var",
477 "--allowlist-file",
478 "--bitfield-enum",
479 "--newtype-enum",
480 "--newtype-global-enum",
481 "--rustified-enum",
482 "--rustified-enum-non-exhaustive",
483 "--constified-enum-module",
484 "--constified-enum",
485 "--type-alias",
486 "--new-type-alias",
487 "--new-type-alias-deref",
488 "--bindgen-wrapper-union",
489 "--manually-drop-union",
490 "--no-partialeq",
491 "--no-copy",
492 "--no-debug",
493 "--no-default",
494 "--no-hash",
495 "--must-use",
496 ])
497 .chain((0..self.abi_overrides.len()).map(|_| "--override-abi"))
498 .map(Some)
499 .collect()
500 } else {
501 vec![None; sets_len]
502 };
503
504 for (regex_set, name) in
505 self.abi_overrides.values_mut().chain(regex_sets).zip(names)
506 {
507 regex_set.build_with_diagnostics(record_matches, name);
508 }
509 }
510 #[cfg(not(feature = "experimental"))]
511 for regex_set in self.abi_overrides.values_mut().chain(regex_sets) {
512 regex_set.build(record_matches);
513 }
514
515 let rust_target = self.rust_target;
516 #[allow(deprecated)]
517 if rust_target <= RustTarget::Stable_1_30 {
518 deprecated_target_diagnostic(rust_target, self);
519 }
520
521 // Disable `untagged_union` if the target does not support it.
522 if !self.rust_features.untagged_union {
523 self.untagged_union = false;
524 }
525 }
526
527 /// Update rust target version
528 pub fn set_rust_target(&mut self, rust_target: RustTarget) {
529 self.rust_target = rust_target;
530
531 // Keep rust_features synced with rust_target
532 self.rust_features = rust_target.into();
533 }
534
535 /// Get features supported by target Rust version
536 pub fn rust_features(&self) -> RustFeatures {
537 self.rust_features
538 }
539
540 fn last_callback<T>(
541 &self,
542 f: impl Fn(&dyn callbacks::ParseCallbacks) -> Option<T>,
543 ) -> Option<T> {
544 self.parse_callbacks
545 .iter()
546 .filter_map(|cb| f(cb.as_ref()))
547 .last()
548 }
549
550 fn all_callbacks<T>(
551 &self,
552 f: impl Fn(&dyn callbacks::ParseCallbacks) -> Vec<T>,
553 ) -> Vec<T> {
554 self.parse_callbacks
555 .iter()
556 .flat_map(|cb| f(cb.as_ref()))
557 .collect()
558 }
559
560 fn process_comment(&self, comment: &str) -> String {
561 let comment = comment::preprocess(comment);
562 self.parse_callbacks
563 .last()
564 .and_then(|cb| cb.process_comment(&comment))
565 .unwrap_or(comment)
566 }
567 }
568
569 fn deprecated_target_diagnostic(target: RustTarget, _options: &BindgenOptions) {
570 let target = String::from(target);
571 warn!("The {} Rust target is deprecated. If you have a good reason to use this target please report it at https://github.com/rust-lang/rust-bindgen/issues", target,);
572
573 #[cfg(feature = "experimental")]
574 if _options.emit_diagnostics {
575 use crate::diagnostics::{Diagnostic, Level};
576
577 let mut diagnostic = Diagnostic::default();
578 diagnostic.with_title(
579 format!("The {} Rust target is deprecated.", target),
580 Level::Warn,
581 );
582 diagnostic.add_annotation(
583 "This Rust target was passed to `--rust-target`",
584 Level::Info,
585 );
586 diagnostic.add_annotation("If you have a good reason to use this target please report it at https://github.com/rust-lang/rust-bindgen/issues", Level::Help);
587 diagnostic.display();
588 }
589 }
590
591 #[cfg(feature = "runtime")]
592 fn ensure_libclang_is_loaded() {
593 if clang_sys::is_loaded() {
594 return;
595 }
596
597 // XXX (issue #350): Ensure that our dynamically loaded `libclang`
598 // doesn't get dropped prematurely, nor is loaded multiple times
599 // across different threads.
600
601 lazy_static! {
602 static ref LIBCLANG: std::sync::Arc<clang_sys::SharedLibrary> = {
603 clang_sys::load().expect("Unable to find libclang");
604 clang_sys::get_library().expect(
605 "We just loaded libclang and it had better still be \
606 here!",
607 )
608 };
609 }
610
611 clang_sys::set_library(Some(LIBCLANG.clone()));
612 }
613
614 #[cfg(not(feature = "runtime"))]
615 fn ensure_libclang_is_loaded() {}
616
617 /// Error type for rust-bindgen.
618 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
619 #[non_exhaustive]
620 pub enum BindgenError {
621 /// The header was a folder.
622 FolderAsHeader(PathBuf),
623 /// Permissions to read the header is insufficient.
624 InsufficientPermissions(PathBuf),
625 /// The header does not exist.
626 NotExist(PathBuf),
627 /// Clang diagnosed an error.
628 ClangDiagnostic(String),
629 /// Code generation reported an error.
630 Codegen(CodegenError),
631 }
632
633 impl std::fmt::Display for BindgenError {
634 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
635 match self {
636 BindgenError::FolderAsHeader(h) => {
637 write!(f, "'{}' is a folder", h.display())
638 }
639 BindgenError::InsufficientPermissions(h) => {
640 write!(f, "insufficient permissions to read '{}'", h.display())
641 }
642 BindgenError::NotExist(h) => {
643 write!(f, "header '{}' does not exist.", h.display())
644 }
645 BindgenError::ClangDiagnostic(message) => {
646 write!(f, "clang diagnosed error: {}", message)
647 }
648 BindgenError::Codegen(err) => {
649 write!(f, "codegen error: {}", err)
650 }
651 }
652 }
653 }
654
655 impl std::error::Error for BindgenError {}
656
657 /// Generated Rust bindings.
658 #[derive(Debug)]
659 pub struct Bindings {
660 options: BindgenOptions,
661 module: proc_macro2::TokenStream,
662 }
663
664 pub(crate) const HOST_TARGET: &str =
665 include_str!(concat!(env!("OUT_DIR"), "/host-target.txt"));
666
667 // Some architecture triplets are different between rust and libclang, see #1211
668 // and duplicates.
669 fn rust_to_clang_target(rust_target: &str) -> String {
670 if rust_target.starts_with("aarch64-apple-") {
671 let mut clang_target = "arm64-apple-".to_owned();
672 clang_target
673 .push_str(rust_target.strip_prefix("aarch64-apple-").unwrap());
674 return clang_target;
675 } else if rust_target.starts_with("riscv64gc-") {
676 let mut clang_target = "riscv64-".to_owned();
677 clang_target.push_str(rust_target.strip_prefix("riscv64gc-").unwrap());
678 return clang_target;
679 } else if rust_target.ends_with("-espidf") {
680 let mut clang_target =
681 rust_target.strip_suffix("-espidf").unwrap().to_owned();
682 clang_target.push_str("-elf");
683 if clang_target.starts_with("riscv32imc-") {
684 clang_target = "riscv32-".to_owned() +
685 clang_target.strip_prefix("riscv32imc-").unwrap();
686 }
687 return clang_target;
688 }
689 rust_target.to_owned()
690 }
691
692 /// Returns the effective target, and whether it was explicitly specified on the
693 /// clang flags.
694 fn find_effective_target(clang_args: &[String]) -> (String, bool) {
695 let mut args = clang_args.iter();
696 while let Some(opt) = args.next() {
697 if opt.starts_with("--target=") {
698 let mut split = opt.split('=');
699 split.next();
700 return (split.next().unwrap().to_owned(), true);
701 }
702
703 if opt == "-target" {
704 if let Some(target) = args.next() {
705 return (target.clone(), true);
706 }
707 }
708 }
709
710 // If we're running from a build script, try to find the cargo target.
711 if let Ok(t) = env::var("TARGET") {
712 return (rust_to_clang_target(&t), false);
713 }
714
715 (rust_to_clang_target(HOST_TARGET), false)
716 }
717
718 impl Bindings {
719 /// Generate bindings for the given options.
720 pub(crate) fn generate(
721 mut options: BindgenOptions,
722 input_unsaved_files: Vec<clang::UnsavedFile>,
723 ) -> Result<Bindings, BindgenError> {
724 ensure_libclang_is_loaded();
725
726 #[cfg(feature = "runtime")]
727 debug!(
728 "Generating bindings, libclang at {}",
729 clang_sys::get_library().unwrap().path().display()
730 );
731 #[cfg(not(feature = "runtime"))]
732 debug!("Generating bindings, libclang linked");
733
734 options.build();
735
736 let (effective_target, explicit_target) =
737 find_effective_target(&options.clang_args);
738
739 let is_host_build =
740 rust_to_clang_target(HOST_TARGET) == effective_target;
741
742 // NOTE: The is_host_build check wouldn't be sound normally in some
743 // cases if we were to call a binary (if you have a 32-bit clang and are
744 // building on a 64-bit system for example). But since we rely on
745 // opening libclang.so, it has to be the same architecture and thus the
746 // check is fine.
747 if !explicit_target && !is_host_build {
748 options
749 .clang_args
750 .insert(0, format!("--target={}", effective_target));
751 };
752
753 fn detect_include_paths(options: &mut BindgenOptions) {
754 if !options.detect_include_paths {
755 return;
756 }
757
758 // Filter out include paths and similar stuff, so we don't incorrectly
759 // promote them to `-isystem`.
760 let clang_args_for_clang_sys = {
761 let mut last_was_include_prefix = false;
762 options
763 .clang_args
764 .iter()
765 .filter(|arg| {
766 if last_was_include_prefix {
767 last_was_include_prefix = false;
768 return false;
769 }
770
771 let arg = &**arg;
772
773 // https://clang.llvm.org/docs/ClangCommandLineReference.html
774 // -isystem and -isystem-after are harmless.
775 if arg == "-I" || arg == "--include-directory" {
776 last_was_include_prefix = true;
777 return false;
778 }
779
780 if arg.starts_with("-I") ||
781 arg.starts_with("--include-directory=")
782 {
783 return false;
784 }
785
786 true
787 })
788 .cloned()
789 .collect::<Vec<_>>()
790 };
791
792 debug!(
793 "Trying to find clang with flags: {:?}",
794 clang_args_for_clang_sys
795 );
796
797 let clang = match clang_sys::support::Clang::find(
798 None,
799 &clang_args_for_clang_sys,
800 ) {
801 None => return,
802 Some(clang) => clang,
803 };
804
805 debug!("Found clang: {:?}", clang);
806
807 // Whether we are working with C or C++ inputs.
808 let is_cpp = args_are_cpp(&options.clang_args) ||
809 options.input_headers.iter().any(|h| file_is_cpp(h));
810
811 let search_paths = if is_cpp {
812 clang.cpp_search_paths
813 } else {
814 clang.c_search_paths
815 };
816
817 if let Some(search_paths) = search_paths {
818 for path in search_paths.into_iter() {
819 if let Ok(path) = path.into_os_string().into_string() {
820 options.clang_args.push("-isystem".to_owned());
821 options.clang_args.push(path);
822 }
823 }
824 }
825 }
826
827 detect_include_paths(&mut options);
828
829 #[cfg(unix)]
830 fn can_read(perms: &std::fs::Permissions) -> bool {
831 use std::os::unix::fs::PermissionsExt;
832 perms.mode() & 0o444 > 0
833 }
834
835 #[cfg(not(unix))]
836 fn can_read(_: &std::fs::Permissions) -> bool {
837 true
838 }
839
840 if let Some(h) = options.input_headers.last() {
841 let path = Path::new(h);
842 if let Ok(md) = std::fs::metadata(path) {
843 if md.is_dir() {
844 return Err(BindgenError::FolderAsHeader(path.into()));
845 }
846 if !can_read(&md.permissions()) {
847 return Err(BindgenError::InsufficientPermissions(
848 path.into(),
849 ));
850 }
851 let h = h.clone();
852 options.clang_args.push(h);
853 } else {
854 return Err(BindgenError::NotExist(path.into()));
855 }
856 }
857
858 for (idx, f) in input_unsaved_files.iter().enumerate() {
859 if idx != 0 || !options.input_headers.is_empty() {
860 options.clang_args.push("-include".to_owned());
861 }
862 options.clang_args.push(f.name.to_str().unwrap().to_owned())
863 }
864
865 debug!("Fixed-up options: {:?}", options);
866
867 let time_phases = options.time_phases;
868 let mut context = BindgenContext::new(options, &input_unsaved_files);
869
870 if is_host_build {
871 debug_assert_eq!(
872 context.target_pointer_size(),
873 std::mem::size_of::<*mut ()>(),
874 "{:?} {:?}",
875 effective_target,
876 HOST_TARGET
877 );
878 }
879
880 {
881 let _t = time::Timer::new("parse").with_output(time_phases);
882 parse(&mut context)?;
883 }
884
885 let (module, options) =
886 codegen::codegen(context).map_err(BindgenError::Codegen)?;
887
888 Ok(Bindings { options, module })
889 }
890
891 /// Write these bindings as source text to a file.
892 pub fn write_to_file<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
893 let file = OpenOptions::new()
894 .write(true)
895 .truncate(true)
896 .create(true)
897 .open(path.as_ref())?;
898 self.write(Box::new(file))?;
899 Ok(())
900 }
901
902 /// Write these bindings as source text to the given `Write`able.
903 pub fn write<'a>(&self, mut writer: Box<dyn Write + 'a>) -> io::Result<()> {
904 if !self.options.disable_header_comment {
905 let version = option_env!("CARGO_PKG_VERSION");
906 let header = format!(
907 "/* automatically generated by rust-bindgen {} */\n\n",
908 version.unwrap_or("(unknown version)")
909 );
910 writer.write_all(header.as_bytes())?;
911 }
912
913 for line in self.options.raw_lines.iter() {
914 writer.write_all(line.as_bytes())?;
915 writer.write_all("\n".as_bytes())?;
916 }
917
918 if !self.options.raw_lines.is_empty() {
919 writer.write_all("\n".as_bytes())?;
920 }
921
922 match self.format_tokens(&self.module) {
923 Ok(formatted_bindings) => {
924 writer.write_all(formatted_bindings.as_bytes())?;
925 }
926 Err(err) => {
927 eprintln!(
928 "Failed to run rustfmt: {} (non-fatal, continuing)",
929 err
930 );
931 writer.write_all(self.module.to_string().as_bytes())?;
932 }
933 }
934 Ok(())
935 }
936
937 /// Gets the rustfmt path to rustfmt the generated bindings.
938 fn rustfmt_path(&self) -> io::Result<Cow<PathBuf>> {
939 debug_assert!(matches!(self.options.formatter, Formatter::Rustfmt));
940 if let Some(ref p) = self.options.rustfmt_path {
941 return Ok(Cow::Borrowed(p));
942 }
943 if let Ok(rustfmt) = env::var("RUSTFMT") {
944 return Ok(Cow::Owned(rustfmt.into()));
945 }
946 #[cfg(feature = "which-rustfmt")]
947 match which::which("rustfmt") {
948 Ok(p) => Ok(Cow::Owned(p)),
949 Err(e) => {
950 Err(io::Error::new(io::ErrorKind::Other, format!("{}", e)))
951 }
952 }
953 #[cfg(not(feature = "which-rustfmt"))]
954 // No rustfmt binary was specified, so assume that the binary is called
955 // "rustfmt" and that it is in the user's PATH.
956 Ok(Cow::Owned("rustfmt".into()))
957 }
958
959 /// Formats a token stream with the formatter set up in `BindgenOptions`.
960 fn format_tokens(
961 &self,
962 tokens: &proc_macro2::TokenStream,
963 ) -> io::Result<String> {
964 let _t = time::Timer::new("rustfmt_generated_string")
965 .with_output(self.options.time_phases);
966
967 match self.options.formatter {
968 Formatter::None => return Ok(tokens.to_string()),
969
970 #[cfg(feature = "prettyplease")]
971 Formatter::Prettyplease => {
972 return Ok(prettyplease::unparse(&syn::parse_quote!(#tokens)));
973 }
974 Formatter::Rustfmt => (),
975 }
976
977 let rustfmt = self.rustfmt_path()?;
978 let mut cmd = Command::new(&*rustfmt);
979
980 cmd.stdin(Stdio::piped()).stdout(Stdio::piped());
981
982 if let Some(path) = self
983 .options
984 .rustfmt_configuration_file
985 .as_ref()
986 .and_then(|f| f.to_str())
987 {
988 cmd.args(["--config-path", path]);
989 }
990
991 let mut child = cmd.spawn()?;
992 let mut child_stdin = child.stdin.take().unwrap();
993 let mut child_stdout = child.stdout.take().unwrap();
994
995 let source = tokens.to_string();
996
997 // Write to stdin in a new thread, so that we can read from stdout on this
998 // thread. This keeps the child from blocking on writing to its stdout which
999 // might block us from writing to its stdin.
1000 let stdin_handle = ::std::thread::spawn(move || {
1001 let _ = child_stdin.write_all(source.as_bytes());
1002 source
1003 });
1004
1005 let mut output = vec![];
1006 io::copy(&mut child_stdout, &mut output)?;
1007
1008 let status = child.wait()?;
1009 let source = stdin_handle.join().expect(
1010 "The thread writing to rustfmt's stdin doesn't do \
1011 anything that could panic",
1012 );
1013
1014 match String::from_utf8(output) {
1015 Ok(bindings) => match status.code() {
1016 Some(0) => Ok(bindings),
1017 Some(2) => Err(io::Error::new(
1018 io::ErrorKind::Other,
1019 "Rustfmt parsing errors.".to_string(),
1020 )),
1021 Some(3) => {
1022 rustfmt_non_fatal_error_diagnostic(
1023 "Rustfmt could not format some lines",
1024 &self.options,
1025 );
1026 Ok(bindings)
1027 }
1028 _ => Err(io::Error::new(
1029 io::ErrorKind::Other,
1030 "Internal rustfmt error".to_string(),
1031 )),
1032 },
1033 _ => Ok(source),
1034 }
1035 }
1036 }
1037
1038 fn rustfmt_non_fatal_error_diagnostic(msg: &str, _options: &BindgenOptions) {
1039 warn!("{}", msg);
1040
1041 #[cfg(feature = "experimental")]
1042 if _options.emit_diagnostics {
1043 use crate::diagnostics::{Diagnostic, Level};
1044
1045 Diagnostic::default()
1046 .with_title(msg, Level::Warn)
1047 .add_annotation(
1048 "The bindings will be generated but not formatted.",
1049 Level::Note,
1050 )
1051 .display();
1052 }
1053 }
1054
1055 impl std::fmt::Display for Bindings {
1056 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1057 let mut bytes = vec![];
1058 self.write(Box::new(&mut bytes) as Box<dyn Write>)
1059 .expect("writing to a vec cannot fail");
1060 f.write_str(
1061 std::str::from_utf8(&bytes)
1062 .expect("we should only write bindings that are valid utf-8"),
1063 )
1064 }
1065 }
1066
1067 /// Determines whether the given cursor is in any of the files matched by the
1068 /// options.
1069 fn filter_builtins(ctx: &BindgenContext, cursor: &clang::Cursor) -> bool {
1070 ctx.options().builtins || !cursor.is_builtin()
1071 }
1072
1073 /// Parse one `Item` from the Clang cursor.
1074 fn parse_one(
1075 ctx: &mut BindgenContext,
1076 cursor: clang::Cursor,
1077 parent: Option<ItemId>,
1078 ) -> clang_sys::CXChildVisitResult {
1079 if !filter_builtins(ctx, &cursor) {
1080 return CXChildVisit_Continue;
1081 }
1082
1083 use clang_sys::CXChildVisit_Continue;
1084 match Item::parse(cursor, parent, ctx) {
1085 Ok(..) => {}
1086 Err(ParseError::Continue) => {}
1087 Err(ParseError::Recurse) => {
1088 cursor.visit(|child| parse_one(ctx, child, parent));
1089 }
1090 }
1091 CXChildVisit_Continue
1092 }
1093
1094 /// Parse the Clang AST into our `Item` internal representation.
1095 fn parse(context: &mut BindgenContext) -> Result<(), BindgenError> {
1096 use clang_sys::*;
1097
1098 let mut error = None;
1099 for d in context.translation_unit().diags().iter() {
1100 let msg = d.format();
1101 let is_err = d.severity() >= CXDiagnostic_Error;
1102 if is_err {
1103 let error = error.get_or_insert_with(String::new);
1104 error.push_str(&msg);
1105 error.push('\n');
1106 } else {
1107 eprintln!("clang diag: {}", msg);
1108 }
1109 }
1110
1111 if let Some(message) = error {
1112 return Err(BindgenError::ClangDiagnostic(message));
1113 }
1114
1115 let cursor = context.translation_unit().cursor();
1116
1117 if context.options().emit_ast {
1118 fn dump_if_not_builtin(cur: &clang::Cursor) -> CXChildVisitResult {
1119 if !cur.is_builtin() {
1120 clang::ast_dump(cur, 0)
1121 } else {
1122 CXChildVisit_Continue
1123 }
1124 }
1125 cursor.visit(|cur| dump_if_not_builtin(&cur));
1126 }
1127
1128 let root = context.root_module();
1129 context.with_module(root, |context| {
1130 cursor.visit(|cursor| parse_one(context, cursor, None))
1131 });
1132
1133 assert!(
1134 context.current_module() == context.root_module(),
1135 "How did this happen?"
1136 );
1137 Ok(())
1138 }
1139
1140 /// Extracted Clang version data
1141 #[derive(Debug)]
1142 pub struct ClangVersion {
1143 /// Major and minor semver, if parsing was successful
1144 pub parsed: Option<(u32, u32)>,
1145 /// full version string
1146 pub full: String,
1147 }
1148
1149 /// Get the major and the minor semver numbers of Clang's version
1150 pub fn clang_version() -> ClangVersion {
1151 ensure_libclang_is_loaded();
1152
1153 //Debian clang version 11.0.1-2
1154 let raw_v: String = clang::extract_clang_version();
1155 let split_v: Option<Vec<&str>> = raw_v
1156 .split_whitespace()
1157 .find(|t| t.chars().next().map_or(false, |v| v.is_ascii_digit()))
1158 .map(|v| v.split('.').collect());
1159 if let Some(v) = split_v {
1160 if v.len() >= 2 {
1161 let maybe_major = v[0].parse::<u32>();
1162 let maybe_minor = v[1].parse::<u32>();
1163 if let (Ok(major), Ok(minor)) = (maybe_major, maybe_minor) {
1164 return ClangVersion {
1165 parsed: Some((major, minor)),
1166 full: raw_v.clone(),
1167 };
1168 }
1169 }
1170 };
1171 ClangVersion {
1172 parsed: None,
1173 full: raw_v.clone(),
1174 }
1175 }
1176
1177 fn env_var<K: AsRef<str> + AsRef<OsStr>>(
1178 parse_callbacks: &[Rc<dyn callbacks::ParseCallbacks>],
1179 key: K,
1180 ) -> Result<String, std::env::VarError> {
1181 for callback in parse_callbacks {
1182 callback.read_env_var(key.as_ref());
1183 }
1184 std::env::var(key)
1185 }
1186
1187 /// Looks for the env var `var_${TARGET}`, and falls back to just `var` when it is not found.
1188 fn get_target_dependent_env_var(
1189 parse_callbacks: &[Rc<dyn callbacks::ParseCallbacks>],
1190 var: &str,
1191 ) -> Option<String> {
1192 if let Ok(target) = env_var(parse_callbacks, "TARGET") {
1193 if let Ok(v) = env_var(parse_callbacks, format!("{}_{}", var, target)) {
1194 return Some(v);
1195 }
1196 if let Ok(v) = env_var(
1197 parse_callbacks,
1198 format!("{}_{}", var, target.replace('-', "_")),
1199 ) {
1200 return Some(v);
1201 }
1202 }
1203
1204 env_var(parse_callbacks, var).ok()
1205 }
1206
1207 /// A ParseCallbacks implementation that will act on file includes by echoing a rerun-if-changed
1208 /// line and on env variable usage by echoing a rerun-if-env-changed line
1209 ///
1210 /// When running inside a `build.rs` script, this can be used to make cargo invalidate the
1211 /// generated bindings whenever any of the files included from the header change:
1212 /// ```
1213 /// use bindgen::builder;
1214 /// let bindings = builder()
1215 /// .header("path/to/input/header")
1216 /// .parse_callbacks(Box::new(bindgen::CargoCallbacks))
1217 /// .generate();
1218 /// ```
1219 #[derive(Debug)]
1220 pub struct CargoCallbacks;
1221
1222 impl callbacks::ParseCallbacks for CargoCallbacks {
1223 fn include_file(&self, filename: &str) {
1224 println!("cargo:rerun-if-changed={}", filename);
1225 }
1226
1227 fn read_env_var(&self, key: &str) {
1228 println!("cargo:rerun-if-env-changed={}", key);
1229 }
1230 }
1231
1232 /// Test command_line_flag function.
1233 #[test]
1234 fn commandline_flag_unit_test_function() {
1235 //Test 1
1236 let bindings = crate::builder();
1237 let command_line_flags = bindings.command_line_flags();
1238
1239 let test_cases = vec![
1240 "--rust-target",
1241 "--no-derive-default",
1242 "--generate",
1243 "functions,types,vars,methods,constructors,destructors",
1244 ]
1245 .iter()
1246 .map(|&x| x.into())
1247 .collect::<Vec<String>>();
1248
1249 assert!(test_cases.iter().all(|x| command_line_flags.contains(x)));
1250
1251 //Test 2
1252 let bindings = crate::builder()
1253 .header("input_header")
1254 .allowlist_type("Distinct_Type")
1255 .allowlist_function("safe_function");
1256
1257 let command_line_flags = bindings.command_line_flags();
1258 let test_cases = vec![
1259 "--rust-target",
1260 "input_header",
1261 "--no-derive-default",
1262 "--generate",
1263 "functions,types,vars,methods,constructors,destructors",
1264 "--allowlist-type",
1265 "Distinct_Type",
1266 "--allowlist-function",
1267 "safe_function",
1268 ]
1269 .iter()
1270 .map(|&x| x.into())
1271 .collect::<Vec<String>>();
1272 println!("{:?}", command_line_flags);
1273
1274 assert!(test_cases.iter().all(|x| command_line_flags.contains(x)));
1275 }
1276
1277 #[test]
1278 fn test_rust_to_clang_target() {
1279 assert_eq!(rust_to_clang_target("aarch64-apple-ios"), "arm64-apple-ios");
1280 }
1281
1282 #[test]
1283 fn test_rust_to_clang_target_riscv() {
1284 assert_eq!(
1285 rust_to_clang_target("riscv64gc-unknown-linux-gnu"),
1286 "riscv64-unknown-linux-gnu"
1287 )
1288 }
1289
1290 #[test]
1291 fn test_rust_to_clang_target_espidf() {
1292 assert_eq!(
1293 rust_to_clang_target("riscv32imc-esp-espidf"),
1294 "riscv32-esp-elf"
1295 );
1296 assert_eq!(
1297 rust_to_clang_target("xtensa-esp32-espidf"),
1298 "xtensa-esp32-elf"
1299 );
1300 }