Skip to main content

padlock_core/
arch.rs

1#[derive(Clone, Copy, Debug, PartialEq)]
2pub enum Endianness {
3    Little,
4    Big,
5}
6
7#[derive(Clone, Copy, Debug, PartialEq)]
8pub struct ArchConfig {
9    pub name: &'static str,
10    pub pointer_size: usize,
11    pub cache_line_size: usize,
12    pub max_align: usize,
13    pub endianness: Endianness,
14}
15
16pub const X86_64_SYSV: ArchConfig = ArchConfig {
17    name: "x86_64",
18    pointer_size: 8,
19    cache_line_size: 64,
20    max_align: 16,
21    endianness: Endianness::Little,
22};
23
24pub const AARCH64: ArchConfig = ArchConfig {
25    name: "aarch64",
26    pointer_size: 8,
27    cache_line_size: 64,
28    max_align: 16,
29    endianness: Endianness::Little,
30};
31
32pub const AARCH64_APPLE: ArchConfig = ArchConfig {
33    name: "aarch64-apple",
34    pointer_size: 8,
35    cache_line_size: 128,
36    max_align: 16,
37    endianness: Endianness::Little,
38};
39
40pub const WASM32: ArchConfig = ArchConfig {
41    name: "wasm32",
42    pointer_size: 4,
43    cache_line_size: 64,
44    max_align: 8,
45    endianness: Endianness::Little,
46};
47
48pub const RISCV64: ArchConfig = ArchConfig {
49    name: "riscv64",
50    pointer_size: 8,
51    cache_line_size: 64,
52    max_align: 16,
53    endianness: Endianness::Little,
54};
55
56/// Create a custom `ArchConfig` by overriding specific fields of a base arch.
57///
58/// Useful for `--cache-line-size` and `--word-size` CLI overrides.
59/// The returned reference is intentionally leaked — CLI binaries are short-lived.
60pub fn with_overrides(
61    base: &ArchConfig,
62    cache_line_size: Option<usize>,
63    word_size: Option<usize>,
64) -> &'static ArchConfig {
65    let ptr = word_size.unwrap_or(base.pointer_size);
66    let max_align = if word_size.is_some() {
67        // 32-bit targets typically cap natural alignment at 8; 64-bit at 16
68        if ptr <= 4 { 8 } else { base.max_align }
69    } else {
70        base.max_align
71    };
72    Box::leak(Box::new(ArchConfig {
73        name: "custom",
74        pointer_size: ptr,
75        cache_line_size: cache_line_size.unwrap_or(base.cache_line_size),
76        max_align,
77        endianness: base.endianness,
78    }))
79}
80
81/// Resolve an architecture name string to a static `ArchConfig` reference.
82///
83/// Accepted values: `x86_64`, `aarch64`, `aarch64_apple`, `wasm32`, `riscv64`.
84pub fn arch_by_name(name: &str) -> Option<&'static ArchConfig> {
85    match name {
86        "x86_64" => Some(&X86_64_SYSV),
87        "aarch64" => Some(&AARCH64),
88        "aarch64_apple" => Some(&AARCH64_APPLE),
89        "wasm32" => Some(&WASM32),
90        "riscv64" => Some(&RISCV64),
91        _ => None,
92    }
93}