Skip to main content

macho_core/model/addr/
ptrauth.rs

1//! Pointer-authentication (arm64e) helpers.
2//!
3//! arm64e encodes a signature in the top 16 bits of a pointer. When dyld
4//! applies fixups it replaces the signature with the authenticated target,
5//! so pointers read from memory in a live process are plain VAs. Static
6//! analysis, though, often sees the raw on-disk form and must strip the
7//! signature bits before dereferencing the pointer or comparing it against
8//! a VA.
9//!
10//! This module exposes the stripping operation as a single, testable helper
11//! rather than scattering bit-masking through metadata readers. Call
12//! [`strip_ptrauth`] on any `u64` that was read directly from the binary on
13//! an arm64e image and is meant to be interpreted as a VA.
14
15/// Mask covering the 48 virtual-address bits used by iOS / macOS arm64e.
16///
17/// Apple silicon uses 48-bit usable VAs and reserves bits 48..=63 for
18/// pointer-auth metadata. Any arm64e pointer with those high bits set is
19/// signed; clearing them yields the VA.
20const PTRAUTH_MASK: u64 = 0x0000_FFFF_FFFF_FFFF;
21
22/// Strip the pointer-authentication signature from an arm64e pointer.
23///
24/// Returns the raw VA with all pointer-auth metadata cleared. Do not use on
25/// non-arm64e pointers: a plain value on x86_64 or arm64 may legitimately
26/// occupy the top bits, and stripping would corrupt it.
27#[inline]
28pub fn strip_ptrauth(raw: u64) -> u64 {
29    raw & PTRAUTH_MASK
30}
31
32/// Whether a `u64` has any bits set that arm64e would interpret as
33/// pointer-auth metadata. A `false` return means [`strip_ptrauth`] is a no-op.
34#[inline]
35pub fn has_ptrauth_bits(raw: u64) -> bool {
36    raw & !PTRAUTH_MASK != 0
37}
38
39#[cfg(test)]
40mod tests {
41    use super::*;
42
43    #[test]
44    fn strips_high_bits() {
45        let signed = 0x8012_3456_dead_beefu64;
46        assert_eq!(strip_ptrauth(signed), 0x0000_3456_dead_beef);
47    }
48
49    #[test]
50    fn noop_when_unsigned() {
51        let plain = 0x0000_0001_dead_beefu64;
52        assert_eq!(strip_ptrauth(plain), plain);
53        assert!(!has_ptrauth_bits(plain));
54    }
55
56    #[test]
57    fn detects_signed_pointer() {
58        assert!(has_ptrauth_bits(0x8012_0000_0000_0000));
59        assert!(!has_ptrauth_bits(0));
60    }
61}