-
Notifications
You must be signed in to change notification settings - Fork 36
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Signed-off-by: Ruoqing He <[email protected]>
- Loading branch information
Showing
5 changed files
with
268 additions
and
95 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
# Supported architectures (arch used in kernel) | ||
SUPPORT_ARCHS = ["arm64", "x86_64", "riscv"] | ||
|
||
# Map arch used in linux kernel to arch understandable for Rust | ||
MAP_RUST_ARCH = {"arm64": "aarch64", "x86_64": "x86_64", "riscv": "riscv64"} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,144 @@ | ||
import re | ||
import os | ||
import subprocess | ||
from pathlib import Path | ||
from lib.kernel_source import prepare_source | ||
from lib import MAP_RUST_ARCH, SUPPORT_ARCHS | ||
|
||
|
||
KVM_BINDINGS_DIR = "kvm-bindings/src/" | ||
|
||
|
||
def generate_kvm_bindings(args): | ||
installed_header_path = prepare_source(args) | ||
|
||
# If arch is not provided, install headers for all supported archs | ||
if args.arch is None: | ||
for arch in SUPPORT_ARCHS: | ||
generate_bindings( | ||
installed_header_path, arch, args.attribute, args.output_path | ||
) | ||
else: | ||
generate_bindings( | ||
installed_header_path, args.arch, args.attribute, args.output_path | ||
) | ||
|
||
|
||
def generate_bindings( | ||
installed_header_path: str, arch: str, attribute: str, output_path: str | ||
): | ||
""" | ||
Generate bindings with source directory support | ||
:param src_dir: Root source directory containing include/ and kvm-bindings/ | ||
:param arch: Target architecture (e.g. aarch64, riscv64, x86_64) | ||
:param attribute: Attribute template for custom structs | ||
:raises RuntimeError: If any generation step fails | ||
""" | ||
try: | ||
# Validate source directory structure | ||
arch_headers = os.path.join(installed_header_path, f"{arch}_headers") | ||
kvm_header = Path(os.path.join(arch_headers, f"include/linux/kvm.h")) | ||
if not kvm_header.is_file(): | ||
raise FileNotFoundError(f"KVM header missing at {kvm_header}") | ||
|
||
arch = MAP_RUST_ARCH[arch] | ||
structs = capture_serde(arch) | ||
if not structs: | ||
raise RuntimeError( | ||
f"No structs found for {arch}, you need to invoke this command under rustvmm/kvm repo root" | ||
) | ||
|
||
# Step 2: Build bindgen command with dynamic paths | ||
base_cmd = [ | ||
"bindgen", | ||
os.path.abspath(kvm_header), # Use absolute path to header | ||
"--impl-debug", | ||
"--impl-partialeq", | ||
"--with-derive-default", | ||
"--with-derive-partialeq", | ||
] | ||
|
||
# Add custom attributes for each struct | ||
for struct in structs: | ||
base_cmd += ["--with-attribute-custom-struct", f"{struct}={attribute}"] | ||
|
||
# Add include paths relative to source directory | ||
base_cmd += ["--", f"-I{arch_headers}/include"] # Use absolute include path | ||
|
||
# Step 3: Execute command with error handling | ||
print(f"\nGenerating bindings for {arch}...") | ||
bindings = subprocess.run( | ||
base_cmd, check=True, capture_output=True, text=True, encoding="utf-8" | ||
).stdout | ||
|
||
print("Successfully generated bindings") | ||
|
||
# Generate architecture-specific filename | ||
output_file_path = f"{output_path}/{arch}/bindings.rs" | ||
|
||
print(f"Generating to: {output_file_path}") | ||
|
||
except subprocess.CalledProcessError as e: | ||
err_msg = f"Bindgen failed (code {e.returncode})" | ||
raise RuntimeError(err_msg) from e | ||
except Exception as e: | ||
raise RuntimeError(f"Generation failed: {str(e)}") from e | ||
|
||
try: | ||
with open(output_file_path, "w") as f: | ||
f.write(bindings) | ||
|
||
# Format with rustfmt | ||
subprocess.run(["rustfmt", output_file_path], check=True) | ||
print(f"Generation succeeded: {output_file_path}") | ||
except subprocess.CalledProcessError: | ||
raise RuntimeError("rustfmt formatting failed") | ||
except IOError as e: | ||
raise RuntimeError(f"File write error: {str(e)}") | ||
|
||
|
||
def capture_serde(arch: str) -> list[str]: | ||
""" | ||
Parse serde implementations for specified architecture | ||
:param arch: Architecture name (e.g. aarch64, riscv64, x86_64) | ||
:return: List of found struct names | ||
:raises FileNotFoundError: When target file is missing | ||
:raises ValueError: When serde_impls block is not found | ||
""" | ||
# Build target file path | ||
target_path = Path(f"{KVM_BINDINGS_DIR}/{arch}/serialize.rs") | ||
|
||
# Validate file existence | ||
if not target_path.is_file(): | ||
raise FileNotFoundError( | ||
f"Serialization file not found for {arch}: {target_path}" | ||
) | ||
|
||
print(f"Extracting serde structs of {arch} from: {target_path}") | ||
|
||
# Read file content | ||
content = target_path.read_text(encoding="utf-8") | ||
|
||
# Multi-line regex pattern to find serde_impls block | ||
pattern = re.compile( | ||
r"serde_impls!\s*\{\s*(?P<struct>.*?)\s*\}", re.DOTALL | re.MULTILINE | ||
) | ||
|
||
# Extract struct list from matched block | ||
match = pattern.search(content) | ||
if not match: | ||
raise ValueError(f"No serde_impls! block found in {target_path}") | ||
|
||
struct_list = match.group("struct") | ||
|
||
structs = [] | ||
for line in struct_list.splitlines(): | ||
# Split and clean individual words | ||
for word in line.split(): | ||
clean_word = word.strip().rstrip(",") | ||
if clean_word: | ||
structs.append(clean_word) | ||
|
||
return structs |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.