|
| 1 | +import re |
| 2 | +import os |
| 3 | +import subprocess |
| 4 | +from pathlib import Path |
| 5 | +from lib.kernel_source import prepare_source |
| 6 | +from lib import MAP_RUST_ARCH, SUPPORT_ARCHS |
| 7 | + |
| 8 | + |
| 9 | +KVM_BINDINGS_DIR = "kvm-bindings/src/" |
| 10 | + |
| 11 | + |
| 12 | +def generate_kvm_bindings(args): |
| 13 | + installed_header_path = prepare_source(args) |
| 14 | + |
| 15 | + # If arch is not provided, install headers for all supported archs |
| 16 | + if args.arch is None: |
| 17 | + for arch in SUPPORT_ARCHS: |
| 18 | + generate_bindings( |
| 19 | + installed_header_path, arch, args.attribute, args.output_path |
| 20 | + ) |
| 21 | + else: |
| 22 | + generate_bindings( |
| 23 | + installed_header_path, args.arch, args.attribute, args.output_path |
| 24 | + ) |
| 25 | + |
| 26 | + |
| 27 | +def generate_bindings( |
| 28 | + installed_header_path: str, arch: str, attribute: str, output_path: str |
| 29 | +): |
| 30 | + """ |
| 31 | + Generate bindings with source directory support |
| 32 | +
|
| 33 | + :param src_dir: Root source directory containing include/ and kvm-bindings/ |
| 34 | + :param arch: Target architecture (e.g. aarch64, riscv64, x86_64) |
| 35 | + :param attribute: Attribute template for custom structs |
| 36 | + :raises RuntimeError: If any generation step fails |
| 37 | + """ |
| 38 | + try: |
| 39 | + # Validate source directory structure |
| 40 | + arch_headers = os.path.join(installed_header_path, f"{arch}_headers") |
| 41 | + kvm_header = Path(os.path.join(arch_headers, f"include/linux/kvm.h")) |
| 42 | + if not kvm_header.is_file(): |
| 43 | + raise FileNotFoundError(f"KVM header missing at {kvm_header}") |
| 44 | + |
| 45 | + arch = MAP_RUST_ARCH[arch] |
| 46 | + structs = capture_serde(arch) |
| 47 | + if not structs: |
| 48 | + raise RuntimeError( |
| 49 | + f"No structs found for {arch}, you need to invoke this command under rustvmm/kvm repo root" |
| 50 | + ) |
| 51 | + |
| 52 | + # Step 2: Build bindgen command with dynamic paths |
| 53 | + base_cmd = [ |
| 54 | + "bindgen", |
| 55 | + os.path.abspath(kvm_header), # Use absolute path to header |
| 56 | + "--impl-debug", |
| 57 | + "--impl-partialeq", |
| 58 | + "--with-derive-default", |
| 59 | + "--with-derive-partialeq", |
| 60 | + ] |
| 61 | + |
| 62 | + # Add custom attributes for each struct |
| 63 | + for struct in structs: |
| 64 | + base_cmd += ["--with-attribute-custom-struct", f"{struct}={attribute}"] |
| 65 | + |
| 66 | + # Add include paths relative to source directory |
| 67 | + base_cmd += ["--", f"-I{arch_headers}/include"] # Use absolute include path |
| 68 | + |
| 69 | + # Step 3: Execute command with error handling |
| 70 | + print(f"\nGenerating bindings for {arch}...") |
| 71 | + bindings = subprocess.run( |
| 72 | + base_cmd, check=True, capture_output=True, text=True, encoding="utf-8" |
| 73 | + ).stdout |
| 74 | + |
| 75 | + print("Successfully generated bindings") |
| 76 | + |
| 77 | + # Generate architecture-specific filename |
| 78 | + output_file_path = f"{output_path}/{arch}/bindings.rs" |
| 79 | + |
| 80 | + print(f"Generating to: {output_file_path}") |
| 81 | + |
| 82 | + except subprocess.CalledProcessError as e: |
| 83 | + err_msg = f"Bindgen failed (code {e.returncode})" |
| 84 | + raise RuntimeError(err_msg) from e |
| 85 | + except Exception as e: |
| 86 | + raise RuntimeError(f"Generation failed: {str(e)}") from e |
| 87 | + |
| 88 | + try: |
| 89 | + with open(output_file_path, "w") as f: |
| 90 | + f.write(bindings) |
| 91 | + |
| 92 | + # Format with rustfmt |
| 93 | + subprocess.run(["rustfmt", output_file_path], check=True) |
| 94 | + print(f"Generation succeeded: {output_file_path}") |
| 95 | + except subprocess.CalledProcessError: |
| 96 | + raise RuntimeError("rustfmt formatting failed") |
| 97 | + except IOError as e: |
| 98 | + raise RuntimeError(f"File write error: {str(e)}") |
| 99 | + |
| 100 | + |
| 101 | +def capture_serde(arch: str) -> list[str]: |
| 102 | + """ |
| 103 | + Parse serde implementations for specified architecture |
| 104 | +
|
| 105 | + :param arch: Architecture name (e.g. aarch64, riscv64, x86_64) |
| 106 | + :return: List of found struct names |
| 107 | + :raises FileNotFoundError: When target file is missing |
| 108 | + :raises ValueError: When serde_impls block is not found |
| 109 | + """ |
| 110 | + # Build target file path |
| 111 | + target_path = Path(f"{KVM_BINDINGS_DIR}/{arch}/serialize.rs") |
| 112 | + |
| 113 | + # Validate file existence |
| 114 | + if not target_path.is_file(): |
| 115 | + raise FileNotFoundError( |
| 116 | + f"Serialization file not found for {arch}: {target_path}" |
| 117 | + ) |
| 118 | + |
| 119 | + print(f"Extracting serde structs of {arch} from: {target_path}") |
| 120 | + |
| 121 | + # Read file content |
| 122 | + content = target_path.read_text(encoding="utf-8") |
| 123 | + |
| 124 | + # Multi-line regex pattern to find serde_impls block |
| 125 | + pattern = re.compile( |
| 126 | + r"serde_impls!\s*\{\s*(?P<struct>.*?)\s*\}", re.DOTALL | re.MULTILINE |
| 127 | + ) |
| 128 | + |
| 129 | + # Extract struct list from matched block |
| 130 | + match = pattern.search(content) |
| 131 | + if not match: |
| 132 | + raise ValueError(f"No serde_impls! block found in {target_path}") |
| 133 | + |
| 134 | + struct_list = match.group("struct") |
| 135 | + |
| 136 | + structs = [] |
| 137 | + for line in struct_list.splitlines(): |
| 138 | + # Split and clean individual words |
| 139 | + for word in line.split(): |
| 140 | + clean_word = word.strip().rstrip(",") |
| 141 | + if clean_word: |
| 142 | + structs.append(clean_word) |
| 143 | + |
| 144 | + return structs |
0 commit comments