Browse Source

aya-gen: add bindgen module and utils to write to file

Alessandro Decina 4 years ago
parent
commit
99447bcc0d
3 changed files with 31 additions and 6 deletions
  1. 13 0
      aya-gen/src/bindgen.rs
  2. 2 6
      aya-gen/src/btf_types.rs
  3. 16 0
      aya-gen/src/lib.rs

+ 13 - 0
aya-gen/src/bindgen.rs

@@ -0,0 +1,13 @@
+use bindgen::{self, Builder, EnumVariation};
+
+pub fn builder() -> Builder {
+    let bindgen = bindgen::builder()
+        .use_core()
+        .ctypes_prefix("::aya_bpf_cty")
+        .layout_tests(false)
+        .clang_arg("-Wno-unknown-attributes")
+        .default_enum_style(EnumVariation::Consts)
+        .prepend_enum_name(false);
+
+    bindgen
+}

+ 2 - 6
aya-gen/src/btf_types.rs

@@ -1,9 +1,9 @@
 use std::{io, path::Path, process::Command, str::from_utf8};
 
-use bindgen::builder;
 use thiserror::Error;
 
 use crate::{
+    bindgen,
     getters::{generate_getters_for_items, probe_read_getter},
     rustfmt,
 };
@@ -28,11 +28,7 @@ pub fn generate<T: AsRef<str>>(
     types: &[T],
     probe_read_getters: bool,
 ) -> Result<String, Error> {
-    let mut bindgen = builder()
-        .use_core()
-        .ctypes_prefix("::aya_bpf_cty")
-        .layout_tests(false)
-        .clang_arg("-Wno-unknown-attributes");
+    let mut bindgen = bindgen::builder();
 
     let c_header = c_header_from_btf(btf_file)?;
     bindgen = bindgen.header_contents("kernel_types.h", &c_header);

+ 16 - 0
aya-gen/src/lib.rs

@@ -1,3 +1,19 @@
+use std::{
+    fs::File,
+    io::{self, Write},
+    path::Path,
+};
+
+pub mod bindgen;
 pub mod btf_types;
 pub mod getters;
 pub mod rustfmt;
+
+pub fn write_to_file<T: AsRef<Path>>(path: T, code: &str) -> Result<(), io::Error> {
+    let mut file = File::create(path)?;
+    file.write_all(code.as_bytes())
+}
+
+pub fn write_to_file_fmt<T: AsRef<Path>>(path: T, code: &str) -> Result<(), io::Error> {
+    write_to_file(path, &rustfmt::format(code)?)
+}