xref: /DragonOS/build-scripts/kernel_build/src/bindgen/mod.rs (revision e26ca418df7af685226d12d7f22fe1785ba163e4)
1*e26ca418SLoGin use std::{path::PathBuf, str::FromStr};
2*e26ca418SLoGin 
3*e26ca418SLoGin use crate::{bindgen::arch::current_bindgenarch, utils::cargo_handler::CargoHandler};
4*e26ca418SLoGin 
5*e26ca418SLoGin mod arch;
6*e26ca418SLoGin 
7*e26ca418SLoGin /// 生成 C->Rust bindings
generate_bindings()8*e26ca418SLoGin pub fn generate_bindings() {
9*e26ca418SLoGin     let wrapper_h = PathBuf::from_str("src/include/bindings/wrapper.h")
10*e26ca418SLoGin         .expect("Failed to parse 'wrapper.h' path");
11*e26ca418SLoGin     CargoHandler::emit_rerun_if_files_changed(&[wrapper_h.clone()]);
12*e26ca418SLoGin 
13*e26ca418SLoGin     let out_path = PathBuf::from(String::from("src/include/bindings/"));
14*e26ca418SLoGin 
15*e26ca418SLoGin     // The bindgen::Builder is the main entry point
16*e26ca418SLoGin     // to bindgen, and lets you build up options for
17*e26ca418SLoGin     // the resulting bindings.
18*e26ca418SLoGin 
19*e26ca418SLoGin     let builder = bindgen::Builder::default()
20*e26ca418SLoGin         .clang_arg("-I./src")
21*e26ca418SLoGin         .clang_arg("-I./src/include")
22*e26ca418SLoGin         // The input header we would like to generate
23*e26ca418SLoGin         // bindings for.
24*e26ca418SLoGin         .header(wrapper_h.to_str().unwrap())
25*e26ca418SLoGin         .blocklist_file("src/include/bindings/bindings.h")
26*e26ca418SLoGin         .clang_arg("-v")
27*e26ca418SLoGin         // 使用core,并将c语言的类型改为core::ffi,而不是使用std库。
28*e26ca418SLoGin         .use_core()
29*e26ca418SLoGin         .ctypes_prefix("::core::ffi")
30*e26ca418SLoGin         .generate_inline_functions(true)
31*e26ca418SLoGin         .raw_line("#![allow(dead_code)]")
32*e26ca418SLoGin         .raw_line("#![allow(non_upper_case_globals)]")
33*e26ca418SLoGin         .raw_line("#![allow(non_camel_case_types)]")
34*e26ca418SLoGin         // Tell cargo to invalidate the built crate whenever any of the
35*e26ca418SLoGin         // included header files changed.
36*e26ca418SLoGin         .parse_callbacks(Box::new(bindgen::CargoCallbacks));
37*e26ca418SLoGin 
38*e26ca418SLoGin     // 处理架构相关的绑定
39*e26ca418SLoGin     let builder = current_bindgenarch().generate_bindings(builder);
40*e26ca418SLoGin 
41*e26ca418SLoGin     // Finish the builder and generate the bindings.
42*e26ca418SLoGin     let bindings = builder
43*e26ca418SLoGin         .generate()
44*e26ca418SLoGin         // Unwrap the Result and panic on failure.
45*e26ca418SLoGin         .expect("Unable to generate bindings");
46*e26ca418SLoGin 
47*e26ca418SLoGin     bindings
48*e26ca418SLoGin         .write_to_file(out_path.join("bindings.rs"))
49*e26ca418SLoGin         .expect("Couldn't write bindings!");
50*e26ca418SLoGin }
51