interplane.Get Omega
Read in your language

omega-mv

Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance.

Brought by drakestapleton

branch main Branches Tags History

omega-mv / research / atemporal / at1 / evaluator / src / scan.rs

210 lines · 9266 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! In-code instruction scan for the isolation gate (AT1 charter G2): a symbol
17//! scan cannot see an inline counter read or an inline system call, so this
18//! reads the executable sections of ELF64 and Mach-O 64 files (objects,
19//! executables, fat binaries and ar archives of them) and looks for
20//! aarch64: MRS from the generic-timer block (CNTVCT_EL0, CNTPCT_EL0, their
21//! self-synchronised forms, CNTFRQ_EL0 ...; word & 0xFFFFF000 == 0xD53BE000),
22//! MRS PMCCNTR_EL0 (0xD53B9D00 | Rt), and SVC #imm (word & 0xFFE0001F == 0xD4000001);
23//! x86_64: RDTSC (0F 31), RDTSCP (0F 01 F9), SYSCALL (0F 05), SYSENTER (0F 34), INT 80h (CD 80).
24//! aarch64 words are 4-byte aligned and exact; the x86 scan is bytewise and can
25//! report a pattern that is only data inside a longer instruction (a false
26//! positive, never a false negative for these encodings).
27
28fn u16le(b: &[u8], o: usize) -> Option<u64> {
29 b.get(o..o + 2).map(|x| u16::from_le_bytes([x[0], x[1]]) as u64)
30}
31fn u32le(b: &[u8], o: usize) -> Option<u64> {
32 b.get(o..o + 4).map(|x| u32::from_le_bytes([x[0], x[1], x[2], x[3]]) as u64)
33}
34fn u32be(b: &[u8], o: usize) -> Option<u64> {
35 b.get(o..o + 4).map(|x| u32::from_be_bytes([x[0], x[1], x[2], x[3]]) as u64)
36}
37fn u64le(b: &[u8], o: usize) -> Option<u64> {
38 b.get(o..o + 8).map(|x| u64::from_le_bytes([x[0], x[1], x[2], x[3], x[4], x[5], x[6], x[7]]))
39}
40
41#[derive(Clone, Copy, PartialEq, Eq)]
42enum Arch {
43 A64,
44 X64,
45 Other,
46}
47
48/// (arch, section name, bytes) for every executable section.
49fn exec_sections<'a>(b: &'a [u8], out: &mut Vec<(Arch, String, &'a [u8])>) -> Result<(), String> {
50 if b.starts_with(b"\x7fELF") {
51 if b.get(4) != Some(&2) || b.get(5) != Some(&1) {
52 return Err("only little-endian ELF64 is supported".into());
53 }
54 let arch = match u16le(b, 0x12) {
55 Some(183) => Arch::A64,
56 Some(62) => Arch::X64,
57 _ => Arch::Other,
58 };
59 let shoff = u64le(b, 0x28).ok_or("truncated ELF header")? as usize;
60 let shentsize = u16le(b, 0x3A).ok_or("truncated")? as usize;
61 let shnum = u16le(b, 0x3C).ok_or("truncated")? as usize;
62 let shstrndx = u16le(b, 0x3E).ok_or("truncated")? as usize;
63 let sh = |i: usize| shoff + i * shentsize;
64 let stroff = u64le(b, sh(shstrndx) + 24).unwrap_or(0) as usize;
65 for i in 0..shnum {
66 let h = sh(i);
67 let typ = u32le(b, h + 4).ok_or("truncated section header")?;
68 let flags = u64le(b, h + 8).ok_or("truncated section header")?;
69 if flags & 0x4 == 0 || typ == 8 {
70 continue;
71 }
72 let off = u64le(b, h + 24).unwrap() as usize;
73 let size = u64le(b, h + 32).unwrap() as usize;
74 let nm = u32le(b, h).unwrap() as usize;
75 let name: String = b.get(stroff + nm..).map(|s| s.iter().take_while(|&&c| c != 0).map(|&c| c as char).collect()).unwrap_or_default();
76 out.push((arch, name, b.get(off..off + size).ok_or("section outside file")?));
77 }
78 return Ok(());
79 }
80 if b.starts_with(&[0xCF, 0xFA, 0xED, 0xFE]) {
81 let arch = match u32le(b, 4) {
82 Some(0x0100000C) => Arch::A64,
83 Some(0x01000007) => Arch::X64,
84 _ => Arch::Other,
85 };
86 let ncmds = u32le(b, 16).ok_or("truncated Mach-O header")? as usize;
87 let mut p = 32usize;
88 for _ in 0..ncmds {
89 let cmd = u32le(b, p).ok_or("truncated load command")?;
90 let size = u32le(b, p + 4).ok_or("truncated load command")? as usize;
91 if cmd == 0x19 {
92 let nsects = u32le(b, p + 64).ok_or("truncated segment")? as usize;
93 for s in 0..nsects {
94 let q = p + 72 + s * 80;
95 let name: String = b.get(q..q + 16).ok_or("truncated section")?.iter().take_while(|&&c| c != 0).map(|&c| c as char).collect();
96 let sz = u64le(b, q + 40).ok_or("truncated section")? as usize;
97 let off = u32le(b, q + 48).ok_or("truncated section")? as usize;
98 let flags = u32le(b, q + 64).ok_or("truncated section")?;
99 if flags & 0x8000_0400 == 0 || flags & 0xff == 1 || off == 0 {
100 continue;
101 }
102 out.push((arch, name, b.get(off..off + sz).ok_or("section outside file")?));
103 }
104 }
105 if size == 0 {
106 return Err("zero-size load command".into());
107 }
108 p += size;
109 }
110 return Ok(());
111 }
112 if b.starts_with(&[0xCA, 0xFE, 0xBA, 0xBE]) {
113 let n = u32be(b, 4).ok_or("truncated fat header")? as usize;
114 for i in 0..n {
115 let q = 8 + i * 20;
116 let off = u32be(b, q + 8).ok_or("truncated fat arch")? as usize;
117 let size = u32be(b, q + 12).ok_or("truncated fat arch")? as usize;
118 exec_sections(b.get(off..off + size).ok_or("fat slice outside file")?, out)?;
119 }
120 return Ok(());
121 }
122 if b.starts_with(b"!<arch>\n") {
123 let mut p = 8usize;
124 while p + 60 <= b.len() {
125 let hdr = &b[p..p + 60];
126 let name = String::from_utf8_lossy(&hdr[0..16]).trim().to_string();
127 let size: usize = String::from_utf8_lossy(&hdr[48..58]).trim().parse().map_err(|_| "bad ar member size")?;
128 let mut data = b.get(p + 60..p + 60 + size).ok_or("ar member outside file")?;
129 if let Some(n) = name.strip_prefix("#1/") {
130 let skip: usize = n.parse().unwrap_or(0);
131 data = data.get(skip..).unwrap_or(&[]);
132 }
133 if data.starts_with(b"\x7fELF") || data.starts_with(&[0xCF, 0xFA, 0xED, 0xFE]) {
134 exec_sections(data, out)?;
135 }
136 p += 60 + size + (size & 1);
137 }
138 return Ok(());
139 }
140 Err("not an ELF64, Mach-O 64, fat or ar file".into())
141}
142
143pub fn scan_bytes(b: &[u8]) -> Result<Vec<String>, String> {
144 let mut secs = Vec::new();
145 exec_sections(b, &mut secs)?;
146 let mut hits = Vec::new();
147 for (arch, name, d) in secs {
148 match arch {
149 Arch::A64 => {
150 for (i, w) in d.chunks_exact(4).enumerate() {
151 let w = u32::from_le_bytes([w[0], w[1], w[2], w[3]]);
152 let what = if w & 0xFFFF_F000 == 0xD53B_E000 {
153 Some("MRS from the generic timer (CNT*_EL0)")
154 } else if w & 0xFFFF_FFE0 == 0xD53B_9D00 {
155 Some("MRS PMCCNTR_EL0 (cycle counter)")
156 } else if w & 0xFFE0_001F == 0xD400_0001 {
157 Some("SVC (raw system call)")
158 } else {
159 None
160 };
161 if let Some(x) = what {
162 hits.push(format!("{} +0x{:x}: {:08x} {}", name, i * 4, w, x));
163 }
164 }
165 }
166 Arch::X64 => {
167 for i in 0..d.len().saturating_sub(1) {
168 let what = match (d[i], d[i + 1], d.get(i + 2).copied()) {
169 (0x0F, 0x31, _) => Some("RDTSC"),
170 (0x0F, 0x01, Some(0xF9)) => Some("RDTSCP"),
171 (0x0F, 0x05, _) => Some("SYSCALL"),
172 (0x0F, 0x34, _) => Some("SYSENTER"),
173 (0xCD, 0x80, _) => Some("INT 80h"),
174 _ => None,
175 };
176 if let Some(x) = what {
177 hits.push(format!("{} +0x{:x}: {} (byte pattern)", name, i, x));
178 }
179 }
180 }
181 Arch::Other => hits.push(format!("{}: unsupported architecture, not scanned", name)),
182 }
183 }
184 Ok(hits)
185}
186
187pub fn main(args: &[&str]) -> i32 {
188 if args.is_empty() {
189 eprintln!("usage: at1-eval scan-clock <object-or-binary>...");
190 return 64;
191 }
192 let mut fail = false;
193 for p in args {
194 match std::fs::read(p).map_err(|e| e.to_string()).and_then(|b| scan_bytes(&b)) {
195 Ok(h) if h.is_empty() => println!("CLEAN {}", p),
196 Ok(h) => {
197 fail = true;
198 for x in h {
199 println!("HIT {} {}", p, x);
200 }
201 }
202 Err(e) => {
203 fail = true;
204 println!("UNREADABLE {} {}", p, e);
205 }
206 }
207 }
208 println!("AT1_CLOCK_SCAN: {}", if fail { "FAIL" } else { "PASS" });
209 if fail { 1 } else { 0 }
210}