All of lore.kernel.org
 help / color / mirror / Atom feed
From: Alejandro Vallejo <alejandro.vallejo@cloud.com>
To: xen-devel@lists.xenproject.org
Cc: Alejandro Vallejo <alejandro.vallejo@cloud.com>,
	Anthony PERARD <anthony.perard@vates.tech>,
	Teddy Astie <teddy.astie@vates.tech>,
	Yann Dirson <yann.dirson@vates.tech>
Subject: [RFC PATCH 05/25] tools/xenbindgen: Add basic plumbing for the C backend
Date: Fri, 15 Nov 2024 11:51:34 +0000	[thread overview]
Message-ID: <20241115115200.2824-6-alejandro.vallejo@cloud.com> (raw)
In-Reply-To: <20241115115200.2824-1-alejandro.vallejo@cloud.com>

Takes an OutFileDef to generate a string with the file content. That
will be all the structs, enums, bitmaps and includes we parse.

For the time being, add the guards only, as the others are implemented
by follow-up patches.

Signed-off-by: Alejandro Vallejo <alejandro.vallejo@cloud.com>
---
 tools/rust/xenbindgen/src/c_lang.rs | 73 +++++++++++++++++++++++++++++
 tools/rust/xenbindgen/src/main.rs   | 54 +++++++++++++++++++--
 tools/rust/xenbindgen/src/spec.rs   |  2 +-
 3 files changed, 125 insertions(+), 4 deletions(-)
 create mode 100644 tools/rust/xenbindgen/src/c_lang.rs

diff --git a/tools/rust/xenbindgen/src/c_lang.rs b/tools/rust/xenbindgen/src/c_lang.rs
new file mode 100644
index 000000000000..f05e36bb362f
--- /dev/null
+++ b/tools/rust/xenbindgen/src/c_lang.rs
@@ -0,0 +1,73 @@
+//! C backend
+//!
+//! A backend for the C programming language. Enums and bitmaps appear as their
+//! backing primitive type. This is in order to mandate size and alignment at
+//! the ABI boundary.
+//!
+//! Otherwise, enums and struct are declared with their native C counterparts,
+//! whereas bitmaps are declared as `#define` items.
+//!
+//! There's an expectation that the supporting library will have the
+//! `(u)int64_aligned_t` types and `XEN_GUEST_HANDLE_64()`, These are important
+//! in order to allow 32bit domains to interact with 64bit hypervisors.
+//!
+//! As far as definitions go, `enums` are stored in native `enums`, but bitmaps
+//! are given in `#define` instead, with an empty struct on top to provide grep
+//! fodder and a tag to follow using an LSP, global, cscope, etc.
+
+use std::fmt::Write;
+
+use crate::spec::OutFileDef;
+
+use convert_case::{Case, Casing};
+
+/// An abstract indentation level. 0 is no indentation, 1 is [`INDENT_WIDTH`]
+/// and so on.
+#[derive(Copy, Clone)]
+struct Indentation(usize);
+
+/// Default width of each level of indentation
+const INDENT_WIDTH: usize = 4;
+
+/// Add a comment to a struct or a field.
+fn comment(out: &mut String, comment: &str, ind: Indentation) {
+    let spaces = " ".repeat(INDENT_WIDTH * ind.0);
+
+    if comment.contains('\n') {
+        writeln!(out, "{spaces}/*").unwrap();
+        for line in comment.split('\n') {
+            write!(out, "{spaces} *").unwrap();
+            if !line.is_empty() {
+                write!(out, " {line}").unwrap();
+            }
+            writeln!(out).unwrap();
+        }
+        writeln!(out, "{spaces} */").unwrap();
+    } else {
+        writeln!(out, "{spaces}/* {comment} */").unwrap();
+    }
+}
+
+/// Generates a single `.h` file.
+///
+/// `filedef` is a language-agnostic high level description of what the output
+/// must contain. The function returns the contents of the new
+///
+/// # Aborts
+/// Aborts the process with `rc=1` on known illegal specifications.
+pub fn parse(filedef: &OutFileDef) -> String {
+    let mut out = String::new();
+    let name = filedef
+        .name
+        .from_case(Case::Kebab)
+        .to_case(Case::UpperSnake);
+    let hdr = format!("{}\n\nAUTOGENERATED. DO NOT MODIFY", filedef.name);
+
+    comment(&mut out, &hdr, Indentation(0));
+    writeln!(out, "#ifndef __XEN_AUTOGEN_{name}_H").unwrap();
+    writeln!(out, "#define __XEN_AUTOGEN_{name}_H\n").unwrap();
+
+    writeln!(out, "#endif /* __XEN_AUTOGEN_{name}_H */\n").unwrap();
+
+    out
+}
diff --git a/tools/rust/xenbindgen/src/main.rs b/tools/rust/xenbindgen/src/main.rs
index 497cf39d3bbd..00abf5ed7f33 100644
--- a/tools/rust/xenbindgen/src/main.rs
+++ b/tools/rust/xenbindgen/src/main.rs
@@ -4,11 +4,15 @@
 
 mod spec;
 
-use std::path::PathBuf;
+mod c_lang;
+
+use std::{io::Write, path::PathBuf};
 
 use clap::Parser;
+use convert_case::{Case, Casing};
 use env_logger::Env;
 use log::{error, info};
+use spec::OutFileDef;
 
 /// A CLI tool to generate struct definitions in several languages.
 #[derive(Parser, Debug)]
@@ -17,6 +21,20 @@ struct Cli {
     /// Path to the input directory containing the hypercall specification
     #[arg(short, long)]
     indir: PathBuf,
+    /// Path to the output directory for the generated bindings.
+    #[arg(short, long)]
+    outdir: PathBuf,
+    /// Target language for the contents of `outdir`.
+    #[arg(short, long, value_enum)]
+    lang: Lang,
+}
+
+/// Supported target languages
+#[derive(clap::ValueEnum, Clone, Debug)]
+#[clap(rename_all = "kebab_case")]
+enum Lang {
+    #[doc(hidden)]
+    C,
 }
 
 fn main() {
@@ -25,7 +43,7 @@ fn main() {
     let cli = Cli::parse();
     info!("args: {:?}", cli);
 
-    let _specification = match spec::Spec::new(&cli.indir) {
+    let specification = match spec::Spec::new(&cli.indir) {
         Ok(x) => x,
         Err(spec::Error::Toml(x)) => {
             error!("TOML parsing error:");
@@ -39,5 +57,35 @@ fn main() {
         }
     };
 
-    todo!("generate output files");
+    let (extension, parser): (&str, fn(&OutFileDef) -> String) = match cli.lang {
+        Lang::C => (".h", c_lang::parse),
+    };
+
+    if let Err(x) = std::fs::create_dir_all(&cli.outdir) {
+        error!("Can't create outdir {:?}: {x}", cli.outdir);
+        std::process::exit(1);
+    }
+
+    for outfile in &specification.0 {
+        let mut path = cli.outdir.clone();
+        let name = outfile.name.from_case(Case::Kebab).to_case(Case::Snake);
+        path.push(format!("{name}{extension}"));
+
+        info!("Generating {path:?}");
+
+        // Parse the input file before creating the output
+        let output = parser(outfile);
+
+        let Ok(mut file) = std::fs::OpenOptions::new()
+            .write(true)
+            .create(true)
+            .truncate(true)
+            .open(path)
+        else {
+            error!("Can't open {}", outfile.name);
+            std::process::exit(1);
+        };
+
+        file.write_all(output.as_bytes()).unwrap();
+    }
 }
diff --git a/tools/rust/xenbindgen/src/spec.rs b/tools/rust/xenbindgen/src/spec.rs
index e69f7c78dc7a..08c4dc3a7eba 100644
--- a/tools/rust/xenbindgen/src/spec.rs
+++ b/tools/rust/xenbindgen/src/spec.rs
@@ -40,7 +40,7 @@ impl OutFileDef {
     pub fn new(name: String, dir: &Path) -> Result<Self, Error> {
         info!("Reading {dir:?} to generate an output file");
 
-        let mut ret = Self { name };
+        let ret = Self { name };
 
         for entry in from_ioerr(dir.read_dir())? {
             let path = from_ioerr(entry)?.path();
-- 
2.47.0



  parent reply	other threads:[~2024-11-15 11:53 UTC|newest]

Thread overview: 51+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2024-11-15 11:51 [RFC PATCH 00/25] Introduce xenbindgen to autogen hypercall structs Alejandro Vallejo
2024-11-15 11:51 ` [RFC PATCH 01/25] xen/domctl: Refine grant_opts into max_grant_version Alejandro Vallejo
2024-11-15 11:51 ` [RFC PATCH 02/25] xen/domctl: Replace altp2m_opts with altp2m_mode Alejandro Vallejo
2024-11-15 11:51 ` [RFC PATCH 03/25] tools/xenbindgen: Introduce a Xen hypercall IDL generator Alejandro Vallejo
2024-11-15 11:51 ` [RFC PATCH 04/25] tools/xenbindgen: Add a TOML spec reader Alejandro Vallejo
2024-11-25 15:13   ` Teddy Astie
2024-11-25 16:51     ` Alejandro Vallejo
2024-11-15 11:51 ` Alejandro Vallejo [this message]
2024-11-15 11:51 ` [RFC PATCH 06/25] tools/xenbindgen: Add xenbindgen's Cargo.lock file Alejandro Vallejo
2024-11-15 11:51 ` [RFC PATCH 07/25] tools/xenbindgen: Add support for structs in TOML specs Alejandro Vallejo
2024-11-25 12:39   ` Teddy Astie
2024-11-25 17:07     ` Alejandro Vallejo
2024-11-25 15:03   ` Teddy Astie
2024-11-25 17:16     ` Alejandro Vallejo
2024-11-15 11:51 ` [RFC PATCH 08/25] tools/xenbindgen: Add support for enums " Alejandro Vallejo
2024-11-25 16:39   ` Teddy Astie
2024-11-25 17:18     ` Alejandro Vallejo
2024-11-15 11:51 ` [RFC PATCH 09/25] tools/xenbindgen: Add support for bitmaps " Alejandro Vallejo
2024-11-15 11:51 ` [RFC PATCH 10/25] tools/xenbindgen: Add support for includes in the " Alejandro Vallejo
2024-11-15 11:51 ` [RFC PATCH 11/25] tools/xenbindgen: Validate ABI rules at generation time Alejandro Vallejo
2024-11-15 11:51 ` [RFC PATCH 12/25] xen: Replace sysctl/readconsole with autogenerated version Alejandro Vallejo
2024-11-25 12:05   ` Jan Beulich
2024-11-25 18:51     ` Alejandro Vallejo
2024-11-26  9:40       ` Jan Beulich
2024-11-26 12:27         ` Alejandro Vallejo
2024-11-26 13:20           ` Jan Beulich
2024-11-26 14:36             ` Alejandro Vallejo
2024-11-26 16:30               ` Jan Beulich
2024-11-26 14:39             ` Teddy Astie
2024-11-26 16:28               ` Jan Beulich
2024-11-15 11:51 ` [RFC PATCH 13/25] xen: Replace hand-crafted altp2m_mode descriptions with autogenerated ones Alejandro Vallejo
2024-11-15 11:51 ` [RFC PATCH 14/25] xen: Replace common bitmaps in domctl.createdomain with autogenerated versions Alejandro Vallejo
2024-11-15 11:51 ` [RFC PATCH 15/25] xen/arm: Replace hand-crafted xen_arch_domainconfig with autogenerated one Alejandro Vallejo
2024-11-15 11:51 ` [RFC PATCH 16/25] xen/x86: " Alejandro Vallejo
2024-11-25 12:09   ` Jan Beulich
2024-11-25 18:53     ` Alejandro Vallejo
2024-11-15 11:51 ` [RFC PATCH 17/25] xen/ppc: Replace empty " Alejandro Vallejo
2024-11-15 11:51 ` [RFC PATCH 18/25] xen/riscv: " Alejandro Vallejo
2024-11-15 11:51 ` [RFC PATCH 19/25] xen: Replace hand-crafted domctl/createdomain with autogenerated version Alejandro Vallejo
2024-12-04 14:48   ` Teddy Astie
2024-11-15 11:51 ` [RFC PATCH 20/25] tools/xen-sys: Create a crate with autogenerated Rust constructs Alejandro Vallejo
2024-11-15 11:51 ` [RFC PATCH 21/25] tools/xenbindgen: Add Rust backend to xenbindgen Alejandro Vallejo
2024-11-15 11:51 ` [RFC PATCH 22/25] tools/xen-sys: Add autogenerated Rust files Alejandro Vallejo
2024-11-15 11:51 ` [RFC PATCH 23/25] licence: Add Unicode-DFS-2016 to the list of licences Alejandro Vallejo
2024-11-15 11:51 ` [RFC PATCH 24/25] tools/rust: Add deny.toml Alejandro Vallejo
2024-11-15 11:51 ` [RFC PATCH 25/25] ci: Add a CI checker for Rust-related helpful properties Alejandro Vallejo
2024-11-21 17:46 ` [RFC PATCH 00/25] Introduce xenbindgen to autogen hypercall structs Anthony PERARD
2024-11-22 10:52   ` Teddy Astie
2024-11-22 13:26     ` Alejandro Vallejo
2024-11-22 13:12   ` Alejandro Vallejo
2024-11-22 16:34     ` Anthony PERARD

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20241115115200.2824-6-alejandro.vallejo@cloud.com \
    --to=alejandro.vallejo@cloud.com \
    --cc=anthony.perard@vates.tech \
    --cc=teddy.astie@vates.tech \
    --cc=xen-devel@lists.xenproject.org \
    --cc=yann.dirson@vates.tech \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.