Skip to content

Commit 32a1e33

Browse files
committed
scripts: Introduce syscall.py
`syscall.py` contains functions used to extract `syscall_table` from headers installed by `kernel_source.py` and generate according Rust code for specific architecture. Signed-off-by: Ruoqing He <[email protected]>
1 parent a592de5 commit 32a1e33

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

scripts/lib/syscall.py

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# Copyright 2025 © Institute of Software, CAS. All rights reserved.
2+
# SPDX-License-Identifier: Apache-2.0
3+
4+
import subprocess
5+
import re
6+
7+
8+
def generate_syscall_table(file_path):
9+
"""Generate syscall table from specified header file"""
10+
try:
11+
with open(file_path, "r") as f:
12+
syscalls = []
13+
pattern = re.compile(r"^#define __NR_(\w+)\s+(\d+)")
14+
15+
for line in f:
16+
line = line.strip()
17+
if line.startswith("#define __NR_"):
18+
match = pattern.match(line)
19+
if match:
20+
name = match.group(1)
21+
num = int(match.group(2))
22+
syscalls.append((name, num))
23+
24+
# Sort alphabetically by syscall name
25+
syscalls.sort(key=lambda x: x[0])
26+
syscall_list = [f'("{name}", {num}),' for name, num in syscalls]
27+
return " ".join(syscall_list)
28+
29+
except FileNotFoundError:
30+
raise RuntimeError(f"Header file not found: {file_path}")
31+
except Exception as e:
32+
raise RuntimeError(f"File processing failed: {str(e)}")
33+
34+
35+
def generate_rust_code(syscalls, output_path):
36+
"""Generate Rust code and format with rustfmt"""
37+
print(f"Generating to: {output_path}")
38+
code = f"""use std::collections::HashMap;
39+
pub(crate) fn make_syscall_table() -> HashMap<&'static str, i64> {{
40+
vec![
41+
{syscalls}
42+
].into_iter().collect()
43+
}}
44+
"""
45+
try:
46+
with open(output_path, "w") as f:
47+
f.write(code)
48+
49+
# Format with rustfmt
50+
subprocess.run(["rustfmt", output_path], check=True)
51+
print(f"Generation succeeded: {output_path}")
52+
except subprocess.CalledProcessError:
53+
raise RuntimeError("rustfmt formatting failed")
54+
except IOError as e:
55+
raise RuntimeError(f"File write error: {str(e)}")

0 commit comments

Comments
 (0)