Skip to main content

ratasm/syscall/
mod.rs

1//! The Linux x86-64 system call database.
2//!
3//! # Where the data comes from
4//!
5//! `assets/syscalls-x86_64.json` is embedded at compile time. The numbers were
6//! taken from the kernel's own `asm/unistd_64.h`, not typed from memory, so
7//! they are exactly what the running kernel expects.
8//!
9//! Roughly sixty calls — the ones an assembly programmer actually writes by
10//! hand — carry a full description: argument names, types, which register each
11//! travels in, the return convention, the errors worth knowing about, and a
12//! NASM example. The remaining entries carry their name and number only and
13//! are marked [`Syscall::detailed`] `== false`. That distinction is deliberate:
14//! a plausible-looking but invented argument list would be worse than an
15//! honest "look at the man page", because the user would act on it.
16//!
17//! # The calling convention
18//!
19//! The number goes in `RAX` and the arguments in `RDI`, `RSI`, `RDX`, `R10`,
20//! `R8`, `R9`. The result comes back in `RAX`, with errors as small negative
21//! values. The fourth argument is in `R10` rather than `RCX` because the
22//! `syscall` instruction itself destroys `RCX` and `R11`.
23
24use serde::{Deserialize, Serialize};
25
26/// The embedded database, parsed on first use.
27const DATABASE_JSON: &str = include_str!("../../assets/syscalls-x86_64.json");
28
29/// One argument of a system call.
30#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
31pub struct Argument {
32    /// The register carrying this argument, such as `rdi`.
33    pub register: String,
34    /// The parameter name from the manual page.
35    pub name: String,
36    /// The C type of the parameter.
37    #[serde(rename = "type")]
38    pub c_type: String,
39    /// What the parameter means, including useful constant values.
40    pub description: String,
41}
42
43impl Argument {
44    /// The register name in upper case, as the register panel shows it.
45    pub fn register_display(&self) -> String {
46        self.register.to_ascii_uppercase()
47    }
48}
49
50/// One system call.
51#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
52pub struct Syscall {
53    /// The number placed in `RAX`.
54    pub number: u32,
55    /// The call's name.
56    pub name: String,
57    /// A one-line summary.
58    pub summary: String,
59    /// The C prototype, when it is modelled.
60    pub signature: Option<String>,
61    /// A coarse category such as `file` or `process`.
62    pub group: String,
63    /// The arguments, in register order.
64    pub args: Vec<Argument>,
65    /// What the call returns in `RAX`.
66    pub returns: Option<String>,
67    /// Errors worth knowing about, as `-ERRNO: explanation`.
68    pub errors: Vec<String>,
69    /// A short NASM example, when one is useful.
70    pub example: Option<String>,
71    /// Whether the arguments and return value are modelled.
72    ///
73    /// `false` means only the name and number are known; nothing else about
74    /// this call has been filled in, and nothing should be inferred.
75    pub detailed: bool,
76}
77
78impl Syscall {
79    /// The number of modelled arguments.
80    pub fn arity(&self) -> usize {
81        self.args.len()
82    }
83
84    /// The argument carried in `register`, if any.
85    pub fn argument_in(&self, register: &str) -> Option<&Argument> {
86        let register = register.trim().to_ascii_lowercase();
87        self.args
88            .iter()
89            .find(|argument| argument.register == register)
90    }
91
92    /// A ready-to-paste NASM snippet setting up the call.
93    ///
94    /// Generated from the argument list when the call has no hand-written
95    /// example, so every detailed call has something to copy.
96    pub fn nasm_template(&self) -> String {
97        if let Some(example) = &self.example {
98            return example.clone();
99        }
100        let mut out = format!(
101            "    mov     rax, {}{:width$}; {}\n",
102            self.number,
103            "",
104            self.name,
105            width = 14usize.saturating_sub(self.number.to_string().len())
106        );
107        for argument in &self.args {
108            out.push_str(&format!(
109                "    mov     {}, {:width$}; {}\n",
110                argument.register,
111                "?",
112                argument.name,
113                width = 18usize.saturating_sub(argument.register.len())
114            ));
115        }
116        out.push_str("    syscall\n");
117        out
118    }
119
120    /// Whether `query` matches this call's name, number or summary.
121    ///
122    /// Matching the number as text as well as numerically means typing `60`
123    /// finds `exit` and typing `exit` finds it too, without a mode switch.
124    pub fn matches(&self, query: &str) -> bool {
125        let query = query.trim().to_ascii_lowercase();
126        if query.is_empty() {
127            return true;
128        }
129        if self.name.to_ascii_lowercase().contains(&query) {
130            return true;
131        }
132        if self.number.to_string() == query {
133            return true;
134        }
135        if let Some(number) = parse_number(&query) {
136            if number == self.number {
137                return true;
138            }
139        }
140        self.summary.to_ascii_lowercase().contains(&query)
141    }
142
143    /// A relevance score for ranking search results; lower sorts first.
144    fn score(&self, query: &str) -> u8 {
145        let query = query.trim().to_ascii_lowercase();
146        let name = self.name.to_ascii_lowercase();
147        if query.is_empty() {
148            return 4;
149        }
150        if name == query || self.number.to_string() == query {
151            0
152        } else if name.starts_with(&query) {
153            1
154        } else if name.contains(&query) {
155            2
156        } else {
157            3
158        }
159    }
160}
161
162/// The syscall calling convention, as described in the database.
163#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
164pub struct Abi {
165    /// The register holding the call number.
166    pub number: String,
167    /// The registers holding arguments, in order.
168    pub arguments: Vec<String>,
169    /// The register holding the return value.
170    #[serde(rename = "return")]
171    pub return_register: String,
172    /// Registers destroyed by the `syscall` instruction.
173    pub clobbered: Vec<String>,
174    /// The instruction used to enter the kernel.
175    pub instruction: String,
176    /// A note explaining the convention's one surprise.
177    pub note: String,
178}
179
180/// The whole database.
181#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
182pub struct Database {
183    /// The architecture the table describes.
184    pub architecture: String,
185    /// The calling convention.
186    pub abi: Abi,
187    /// Where the data came from.
188    pub source: String,
189    /// Every system call, ordered by number.
190    pub syscalls: Vec<Syscall>,
191}
192
193impl Database {
194    /// Parses the embedded database.
195    ///
196    /// # Errors
197    ///
198    /// Returns an error if the embedded asset is not valid JSON, which would
199    /// mean the build is broken; a test in this module checks it at build
200    /// time so it cannot reach a user.
201    pub fn load() -> Result<Self, serde_json::Error> {
202        serde_json::from_str(DATABASE_JSON)
203    }
204
205    /// Looks up a call by number.
206    pub fn by_number(&self, number: u32) -> Option<&Syscall> {
207        self.syscalls.iter().find(|call| call.number == number)
208    }
209
210    /// Looks up a call by exact name, case-insensitively.
211    pub fn by_name(&self, name: &str) -> Option<&Syscall> {
212        let name = name.trim().to_ascii_lowercase();
213        self.syscalls
214            .iter()
215            .find(|call| call.name.to_ascii_lowercase() == name)
216    }
217
218    /// Searches names, numbers and summaries, best match first.
219    ///
220    /// An empty query returns every call in number order, which is what the
221    /// search panel shows before the user types anything.
222    pub fn search(&self, query: &str) -> Vec<&Syscall> {
223        let mut found: Vec<&Syscall> = self
224            .syscalls
225            .iter()
226            .filter(|call| call.matches(query))
227            .collect();
228        found.sort_by_key(|call| (call.score(query), call.number));
229        found
230    }
231
232    /// Every call in a group, such as `file` or `process`.
233    pub fn in_group(&self, group: &str) -> Vec<&Syscall> {
234        self.syscalls
235            .iter()
236            .filter(|call| call.group == group)
237            .collect()
238    }
239
240    /// The calls whose arguments are fully modelled.
241    pub fn detailed(&self) -> Vec<&Syscall> {
242        self.syscalls.iter().filter(|call| call.detailed).collect()
243    }
244
245    /// The number of calls in the table.
246    pub fn len(&self) -> usize {
247        self.syscalls.len()
248    }
249
250    /// Whether the table is empty, which would indicate a broken asset.
251    pub fn is_empty(&self) -> bool {
252        self.syscalls.is_empty()
253    }
254}
255
256/// Parses a syscall number written in decimal or hexadecimal.
257fn parse_number(text: &str) -> Option<u32> {
258    let text = text.trim();
259    if let Some(hex) = text.strip_prefix("0x").or_else(|| text.strip_prefix("0X")) {
260        u32::from_str_radix(hex, 16).ok()
261    } else {
262        text.parse().ok()
263    }
264}
265
266#[cfg(test)]
267mod tests {
268    use super::*;
269
270    fn database() -> Database {
271        Database::load().expect("the embedded database must parse")
272    }
273
274    #[test]
275    fn the_embedded_database_parses() {
276        let db = database();
277        assert!(!db.is_empty());
278        assert_eq!(db.architecture, "x86_64");
279        assert!(db.len() > 300, "expected the full table, got {}", db.len());
280    }
281
282    #[test]
283    fn well_known_numbers_are_correct() {
284        // These are the numbers a Linux assembly programmer memorises; if any
285        // of them is wrong the whole table is suspect.
286        let db = database();
287        for (name, number) in [
288            ("read", 0),
289            ("write", 1),
290            ("open", 2),
291            ("close", 3),
292            ("mmap", 9),
293            ("exit", 60),
294            ("exit_group", 231),
295            ("openat", 257),
296        ] {
297            let call = db.by_name(name).unwrap_or_else(|| panic!("{name} missing"));
298            assert_eq!(call.number, number, "{name} has the wrong number");
299        }
300    }
301
302    #[test]
303    fn numbers_are_unique_and_ordered() {
304        let db = database();
305        let mut previous = None;
306        for call in &db.syscalls {
307            if let Some(previous) = previous {
308                assert!(call.number > previous, "numbers must increase");
309            }
310            previous = Some(call.number);
311        }
312    }
313
314    #[test]
315    fn names_are_unique() {
316        let db = database();
317        let mut names: Vec<&str> = db.syscalls.iter().map(|call| call.name.as_str()).collect();
318        let count = names.len();
319        names.sort_unstable();
320        names.dedup();
321        assert_eq!(names.len(), count, "duplicate syscall names");
322    }
323
324    #[test]
325    fn the_abi_matches_the_linux_convention() {
326        let db = database();
327        assert_eq!(db.abi.number, "rax");
328        assert_eq!(db.abi.arguments, ["rdi", "rsi", "rdx", "r10", "r8", "r9"]);
329        assert_eq!(db.abi.return_register, "rax");
330        assert_eq!(db.abi.clobbered, ["rcx", "r11"]);
331        assert_eq!(db.abi.instruction, "syscall");
332        assert!(
333            db.abi.note.contains("R10"),
334            "the R10 trap must be explained"
335        );
336    }
337
338    #[test]
339    fn the_abi_agrees_with_the_register_model() {
340        // Two independent sources of the same fact must not drift apart.
341        use crate::instruction::registers;
342        let db = database();
343        let from_registers: Vec<String> = registers::syscall_argument_registers()
344            .iter()
345            .map(|register| register.name.to_owned())
346            .collect();
347        assert_eq!(db.abi.arguments, from_registers);
348    }
349
350    #[test]
351    fn arguments_are_assigned_to_the_right_registers() {
352        let db = database();
353        let write = db.by_name("write").expect("write");
354        assert_eq!(write.arity(), 3);
355        assert_eq!(write.args[0].register, "rdi");
356        assert_eq!(write.args[1].register, "rsi");
357        assert_eq!(write.args[2].register, "rdx");
358        assert_eq!(write.args[0].name, "fd");
359        assert_eq!(
360            write.argument_in("RSI").map(|a| a.name.as_str()),
361            Some("buf")
362        );
363    }
364
365    #[test]
366    fn a_six_argument_call_uses_r10_for_the_fourth() {
367        // The detail the whole ABI section exists to make obvious.
368        let db = database();
369        let mmap = db.by_name("mmap").expect("mmap");
370        assert_eq!(mmap.arity(), 6);
371        let registers: Vec<&str> = mmap.args.iter().map(|a| a.register.as_str()).collect();
372        assert_eq!(registers, ["rdi", "rsi", "rdx", "r10", "r8", "r9"]);
373    }
374
375    #[test]
376    fn detailed_calls_carry_a_return_description_and_errors() {
377        let db = database();
378        for call in db.detailed() {
379            assert!(
380                call.returns.is_some(),
381                "{} is marked detailed but has no return description",
382                call.name
383            );
384            assert!(
385                call.signature.is_some(),
386                "{} is marked detailed but has no signature",
387                call.name
388            );
389            assert!(!call.summary.is_empty(), "{} has no summary", call.name);
390        }
391        assert!(db.detailed().len() >= 50, "too few detailed entries");
392    }
393
394    #[test]
395    fn undetailed_calls_claim_nothing_they_do_not_know() {
396        // The honesty property: an entry without data must not invent any.
397        let db = database();
398        for call in db.syscalls.iter().filter(|call| !call.detailed) {
399            assert!(call.args.is_empty(), "{} invented arguments", call.name);
400            assert!(call.returns.is_none(), "{} invented a return", call.name);
401            assert!(call.errors.is_empty(), "{} invented errors", call.name);
402            assert!(call.example.is_none(), "{} invented an example", call.name);
403            assert!(
404                call.summary.contains("man 2"),
405                "{} should point at the manual page",
406                call.name
407            );
408        }
409    }
410
411    #[test]
412    fn search_by_name_ranks_the_exact_match_first() {
413        let db = database();
414        let found = db.search("write");
415        assert_eq!(found.first().map(|call| call.name.as_str()), Some("write"));
416        assert!(found.len() > 1, "related calls should also be offered");
417    }
418
419    #[test]
420    fn search_by_number_finds_the_call() {
421        let db = database();
422        let found = db.search("60");
423        assert_eq!(found.first().map(|call| call.name.as_str()), Some("exit"));
424    }
425
426    #[test]
427    fn search_by_hexadecimal_number_works() {
428        let db = database();
429        let found = db.search("0x3c");
430        assert!(found.iter().any(|call| call.name == "exit"));
431    }
432
433    #[test]
434    fn search_matches_the_description() {
435        let db = database();
436        let found = db.search("random");
437        assert!(found.iter().any(|call| call.name == "getrandom"));
438    }
439
440    #[test]
441    fn search_is_case_insensitive() {
442        let db = database();
443        assert!(db.search("WRITE").iter().any(|call| call.name == "write"));
444    }
445
446    #[test]
447    fn an_empty_query_lists_everything_in_number_order() {
448        let db = database();
449        let found = db.search("");
450        assert_eq!(found.len(), db.len());
451        assert_eq!(found[0].number, 0);
452    }
453
454    #[test]
455    fn a_query_matching_nothing_returns_nothing() {
456        let db = database();
457        assert!(db.search("zzzzzznotasyscall").is_empty());
458    }
459
460    #[test]
461    fn lookup_by_name_is_case_insensitive_and_trims() {
462        let db = database();
463        assert!(db.by_name("  WRITE ").is_some());
464        assert!(db.by_name("no_such_call").is_none());
465    }
466
467    #[test]
468    fn lookup_by_number_finds_and_misses_correctly() {
469        let db = database();
470        assert_eq!(db.by_number(1).map(|c| c.name.as_str()), Some("write"));
471        assert!(db.by_number(99_999).is_none());
472    }
473
474    #[test]
475    fn a_hand_written_example_is_used_verbatim() {
476        let db = database();
477        let write = db.by_name("write").expect("write");
478        let template = write.nasm_template();
479        assert!(template.contains("mov     rax, 1"));
480        assert!(template.contains("syscall"));
481    }
482
483    #[test]
484    fn a_template_is_generated_for_calls_without_an_example() {
485        let db = database();
486        let call = db
487            .detailed()
488            .into_iter()
489            .find(|call| call.example.is_none() && call.arity() > 0)
490            .expect("a detailed call without an example");
491        let template = call.nasm_template();
492        assert!(template.contains(&format!("mov     rax, {}", call.number)));
493        assert!(template.contains("syscall"));
494        for argument in &call.args {
495            assert!(
496                template.contains(&argument.register),
497                "{} missing from the template",
498                argument.register
499            );
500        }
501    }
502
503    #[test]
504    fn generated_templates_lex_as_valid_assembly_lines() {
505        // A template that does not survive the lexer would render wrongly.
506        use crate::editor::syntax;
507        let db = database();
508        for call in db.detailed() {
509            for line in call.nasm_template().lines() {
510                let covered: usize = syntax::tokenize(line)
511                    .iter()
512                    .map(crate::editor::Token::len)
513                    .sum();
514                assert_eq!(covered, line.len(), "{}: {line:?}", call.name);
515            }
516        }
517    }
518
519    #[test]
520    fn groups_partition_the_detailed_calls() {
521        let db = database();
522        assert!(!db.in_group("file").is_empty());
523        assert!(!db.in_group("process").is_empty());
524        assert!(!db.in_group("memory").is_empty());
525        assert!(db.in_group("no-such-group").is_empty());
526    }
527
528    #[test]
529    fn errors_are_written_in_the_negative_errno_form() {
530        // Syscalls return errors as small negative values in RAX, and the
531        // text must teach that rather than the C wrapper's -1/errno split.
532        let db = database();
533        for call in db.detailed() {
534            for error in &call.errors {
535                assert!(
536                    error.starts_with("-E"),
537                    "{}: {error:?} should be a negative errno",
538                    call.name
539                );
540            }
541        }
542    }
543}