ruwrite_macros/lib.rs
1//! Implementation detail of `ruwrite`. Depend on `ruwrite` and use
2//! `ruwrite::protect`; nothing here is meant to be used directly.
3
4use proc_macro::TokenStream;
5use quote::quote;
6use syn::{parse_macro_input, Ident, Item};
7
8const MAGIC: &[u8; 8] = b"RUWPROT2";
9
10/// `RUWPROT2` record: `magic | target_kind(1) | mode(1) | name_encoding(1) |
11/// name_len(2, little-endian) | name or hash`. See `ruwrite::protect` for
12/// what each field means; this function only lays out the bytes.
13fn build_record(target_kind: u8, mode: u8, name: &str, hide_name: bool) -> Vec<u8> {
14 let (name_encoding, payload): (u8, Vec<u8>) = if hide_name {
15 (1, fnv1a64(name).to_le_bytes().to_vec())
16 } else {
17 (0, name.as_bytes().to_vec())
18 };
19 let mut record = Vec::with_capacity(11 + payload.len());
20 record.extend_from_slice(MAGIC);
21 record.push(target_kind);
22 record.push(mode);
23 record.push(name_encoding);
24 record.extend_from_slice(&(payload.len() as u16).to_le_bytes());
25 record.extend_from_slice(&payload);
26 record
27}
28
29/// Same hash `ruwrite` uses to recognise a hidden name without storing it in
30/// the binary. Not cryptographic: it only needs to be stable and cheap.
31fn fnv1a64(s: &str) -> u64 {
32 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
33 for b in s.as_bytes() {
34 hash ^= u64::from(*b);
35 hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
36 }
37 hash
38}
39
40/// Declares how `ruwrite` is allowed to treat the function or `static` it is
41/// placed on.
42///
43/// ```ignore
44/// # use ruwrite::protect;
45/// #[protect(immutable)]
46/// fn check_license() -> bool { true }
47///
48/// #[protect(protected)]
49/// static SECRET_KEY: u32 = 0xDEAD_BEEF;
50/// ```
51///
52/// Modes, from least to most restrictive:
53///
54/// | Mode | Meaning |
55/// |------|---------|
56/// | `editable` | explicitly not protected; the same as writing nothing, spelled out |
57/// | `immutable` | `ruwrite` refuses every edit that touches it |
58/// | `protected` | `immutable`, and also included when the program later checks its own integrity (see `Executable::integrity_snapshot`) |
59/// | `hide` | `immutable`, and its name is not stored as readable text in the binary and is left out of `Executable::functions()` / `variables()`; see the limitations below |
60///
61/// `ruwrite` reads this declaration back from the compiled executable, so
62/// every edit through it is checked, however it is made: by name, by address,
63/// by raw bytes, or by content ([`Executable::find_value`]). It is the
64/// program declaring the rule, not `ruwrite` guessing at one — there is
65/// deliberately no option to bypass it.
66///
67/// **What `hide` does and does not do.** It keeps the plain name out of the
68/// `.ruwprot` record (a hash is stored instead, so `ruwrite` can still match
69/// the right item without ever holding its readable name) and filters it out
70/// of `ruwrite`'s own listings. It does not rename the function's debug or
71/// symbol-table entry, strip its machine code, or defend against
72/// disassembly: a determined reader with `objdump` still sees it. Build
73/// without debug info and strip symbols for that.
74///
75/// Mark a protected function `#[inline(never)]` so the compiler keeps one
76/// identifiable copy of it instead of folding it into every caller.
77#[proc_macro_attribute]
78pub fn protect(attr: TokenStream, item: TokenStream) -> TokenStream {
79 let mode_ident = parse_macro_input!(attr as Ident);
80 let mode_name = mode_ident.to_string();
81 let mode: u8 = match mode_name.as_str() {
82 "editable" => 0,
83 "immutable" => 1,
84 "protected" => 2,
85 "hide" => 3,
86 other => {
87 return syn::Error::new(
88 mode_ident.span(),
89 format!(
90 "unknown mode `{other}` for `#[ruwrite::protect(..)]`; \
91 expected one of: editable, immutable, protected, hide"
92 ),
93 )
94 .to_compile_error()
95 .into();
96 }
97 };
98
99 let parsed = parse_macro_input!(item as Item);
100 let (name, target_kind) = match &parsed {
101 Item::Fn(f) => (f.sig.ident.to_string(), 1u8),
102 Item::Static(s) => (s.ident.to_string(), 2u8),
103 other => {
104 return syn::Error::new_spanned(
105 other,
106 "`#[ruwrite::protect(..)]` can only be placed on a `fn` or a `static`",
107 )
108 .to_compile_error()
109 .into();
110 }
111 };
112
113 if mode == 0 {
114 // `editable` : rien à faire respecter, donc rien à embarquer non plus.
115 return quote! { #parsed }.into();
116 }
117
118 let record = build_record(target_kind, mode, &name, mode == 3);
119 let len = record.len();
120 let bytes = record.iter().copied();
121
122 quote! {
123 #parsed
124
125 const _: () = {
126 #[used]
127 #[cfg_attr(
128 any(target_os = "macos", target_os = "ios"),
129 link_section = "__DATA,__ruwprot"
130 )]
131 #[cfg_attr(not(any(target_os = "macos", target_os = "ios")), link_section = ".ruwprot")]
132 static RUWRITE_RECORD: [u8; #len] = [ #(#bytes),* ];
133 };
134 }
135 .into()
136}
137
138#[cfg(test)]
139mod tests {
140 use super::*;
141
142 #[test]
143 fn plain_record_layout() {
144 let r = build_record(1, 1, "check", false);
145 assert_eq!(&r[..8], MAGIC);
146 assert_eq!(r[8], 1); // function
147 assert_eq!(r[9], 1); // immutable
148 assert_eq!(r[10], 0); // plain name
149 assert_eq!(&r[11..13], [5, 0]);
150 assert_eq!(&r[13..], b"check");
151 }
152
153 #[test]
154 fn hidden_record_stores_a_hash_not_the_name() {
155 let r = build_record(1, 3, "secret_fn", true);
156 assert_eq!(r[9], 3); // hide
157 assert_eq!(r[10], 1); // hashed
158 assert_eq!(&r[11..13], [8, 0]);
159 assert_eq!(r.len(), 21);
160 assert!(
161 r.windows(9).all(|w| w != b"secret_fn"),
162 "the plain name must not appear in the record"
163 );
164 }
165
166 #[test]
167 fn hash_is_deterministic() {
168 assert_eq!(fnv1a64("check"), fnv1a64("check"));
169 assert_ne!(fnv1a64("check"), fnv1a64("checked"));
170 }
171}