interplane.Get Omega
Read in your language

atlas

aien-dev/atlas

Brought by drakestapleton

branch master Branches Tags History

atlas / tools / m1tool.c

1150 lines · 47841 bytes Raw Blame History
1/*
2 * m1tool -- ATLAS M1 host qualification tool (no Python).
3 * Host: Linux / AArch64 / x86_64.
4 *
5 * Built with host gcc, linking sha256_clean.c from repo root.
6 *
7 * Subcommands:
8 * sha256 <file>
9 * hexfield <file> <offset> <width 1|2|4|8>
10 * bytes <file> <offset> <len>
11 * audit-verify <atlas.bin> <atlas.sha256> <atlas.manifest> <machine_contract.json> <atlas.audit> <atlas.decode>
12 * gen-audit <atlas.bin> <atlas.elf> <out.audit> <out.decode>
13 * mutate-sweep <in.bin> <offset> <out.bin>
14 * mutate-adv <in.bin> <scenario 0..11> <out.bin>
15 * qemu-run <atlas.bin> <physics.bin> [timeout_ms]
16 * qemu-matrix <atlas.bin> <physics.bin>
17 */
18
19#define _GNU_SOURCE
20#include <ctype.h>
21#include <errno.h>
22#include <fcntl.h>
23#include <poll.h>
24#include <signal.h>
25#include <stdarg.h>
26#include <stdint.h>
27#include <stdio.h>
28#include <stdlib.h>
29#include <string.h>
30#include <sys/stat.h>
31#include <sys/types.h>
32#include <sys/wait.h>
33#include <time.h>
34#include <unistd.h>
35
36/* Repo-root audited SHA-256 */
37void sha256_compute(const uint8_t *data, uint64_t len, uint8_t scratch_buf[128],
38 uint32_t out_digest[8]);
39
40#define M1_MAX_FILE (64 * 1024 * 1024)
41
42static int fail(const char *fmt, ...) {
43 va_list ap;
44 va_start(ap, fmt);
45 fprintf(stderr, "m1tool: ");
46 vfprintf(stderr, fmt, ap);
47 fputc('\n', stderr);
48 va_end(ap);
49 return 1;
50}
51
52static int read_file(const char *path, uint8_t **out, uint64_t *out_len) {
53 FILE *f = fopen(path, "rb");
54 if (!f) return fail("cannot open %s", path);
55 fseek(f, 0, SEEK_END);
56 long sz = ftell(f);
57 if (sz < 0) { fclose(f); return fail("ftell failed on %s", path); }
58 fseek(f, 0, SEEK_SET);
59
60 uint8_t *buf = malloc(sz + 1);
61 if (!buf) { fclose(f); return fail("out of memory reading %s", path); }
62 size_t n = fread(buf, 1, sz, f);
63 fclose(f);
64 if (n != (size_t)sz) { free(buf); return fail("short read on %s", path); }
65 buf[sz] = '\0';
66 *out = buf;
67 *out_len = sz;
68 return 0;
69}
70
71static int parse_u64(const char *s, uint64_t *v) {
72 if (!s || !*s || *s == '-' || *s == '+' || *s == ' ') return fail("bad number: %s", s ? s : "(null)");
73 char *end; errno = 0;
74 unsigned long long x = strtoull(s, &end, 0);
75 if (errno || *end) return fail("bad number: %s", s);
76 *v = x;
77 return 0;
78}
79
80/* objdump's literal operand is hexadecimal and must terminate before metadata. */
81static int parse_literal(const char *s, uint64_t *value) {
82 if (!isxdigit((unsigned char)*s)) return 0;
83 char *end;
84 errno = 0;
85 unsigned long long parsed = strtoull(s, &end, 16);
86 if (errno || end == s || (*end && *end != ' ' && *end != '\t' &&
87 *end != '<' && *end != '\n')) return 0;
88 *value = parsed;
89 return 1;
90}
91
92static void put_hex(const uint8_t *p, uint64_t n) {
93 for (uint64_t i = 0; i < n; i++) printf("%02x", p[i]);
94}
95
96static void sha256_file_buf(const uint8_t *buf, uint64_t len, uint8_t out[32]) {
97 uint8_t scratch[128] __attribute__((aligned(16)));
98 uint32_t st[8];
99 sha256_compute(buf, len, scratch, st);
100 for (int i = 0; i < 8; i++) {
101 out[4 * i + 0] = (uint8_t)(st[i] >> 24);
102 out[4 * i + 1] = (uint8_t)(st[i] >> 16);
103 out[4 * i + 2] = (uint8_t)(st[i] >> 8);
104 out[4 * i + 3] = (uint8_t)(st[i]);
105 }
106}
107
108static int sha256_to_hex(const uint8_t d[32], char hex[65]) {
109 for (int i = 0; i < 32; i++) sprintf(hex + 2 * i, "%02x", d[i]);
110 hex[64] = '\0';
111 return 0;
112}
113
114static int cmd_sha256(int argc, char **argv) {
115 if (argc != 2) return fail("usage: %s <file>", argv[0]);
116 uint8_t *buf; uint64_t len; uint8_t d[32];
117 if (read_file(argv[1], &buf, &len)) return 1;
118 sha256_file_buf(buf, len, d);
119 free(buf);
120 put_hex(d, 32); putchar('\n');
121 return 0;
122}
123
124static int cmd_hexfield(int argc, char **argv) {
125 if (argc != 4) return fail("usage: %s <file> <offset> <width 1|2|4|8>", argv[0]);
126 uint64_t w, off, len, v = 0; uint8_t *buf;
127 if (parse_u64(argv[3], &w)) return 1;
128 if (w != 1 && w != 2 && w != 4 && w != 8) return fail("width must be 1, 2, 4 or 8: %s", argv[3]);
129 if (parse_u64(argv[2], &off)) return 1;
130 if (read_file(argv[1], &buf, &len)) return 1;
131 if (off > len || w > len - off) { free(buf); return fail("range outside file %s", argv[1]); }
132 for (uint64_t i = 0; i < w; i++) v |= (uint64_t)buf[off + i] << (8 * i);
133 free(buf);
134 printf("0x%0*llx\n", (int)(2 * w), (unsigned long long)v);
135 return 0;
136}
137
138static int cmd_bytes(int argc, char **argv) {
139 if (argc != 4) return fail("usage: %s <file> <offset> <len>", argv[0]);
140 uint64_t n, off, len; uint8_t *buf;
141 if (parse_u64(argv[3], &n)) return 1;
142 if (parse_u64(argv[2], &off)) return 1;
143 if (read_file(argv[1], &buf, &len)) return 1;
144 if (off > len || n > len - off) { free(buf); return fail("range outside file %s", argv[1]); }
145 put_hex(buf + off, n); putchar('\n');
146 free(buf);
147 return 0;
148}
149
150/* -------------------------------------------------------------------------
151 * Audit Verification (Seam 1)
152 * ------------------------------------------------------------------------- */
153
154static char *json_extract_str(const char *json, const char *key, char *out, size_t out_cap) {
155 char pattern[256];
156 snprintf(pattern, sizeof(pattern), "\"%s\"", key);
157 const char *p = strstr(json, pattern);
158 if (!p) return NULL;
159 p += strlen(pattern);
160 while (*p && (*p == ' ' || *p == ':' || *p == '\t' || *p == '\n' || *p == '\r')) p++;
161 if (*p == '\"') {
162 p++;
163 const char *end = strchr(p, '\"');
164 if (!end) return NULL;
165 size_t n = (size_t)(end - p);
166 if (n >= out_cap) n = out_cap - 1;
167 memcpy(out, p, n);
168 out[n] = '\0';
169 return out;
170 }
171 return NULL;
172}
173
174static int json_extract_u64(const char *json, const char *key, uint64_t *val) {
175 char pattern[256];
176 snprintf(pattern, sizeof(pattern), "\"%s\"", key);
177 const char *p = strstr(json, pattern);
178 if (!p) return -1;
179 p += strlen(pattern);
180 while (*p && (*p == ' ' || *p == ':' || *p == '\t' || *p == '\n' || *p == '\r')) p++;
181 if (*p == '\"') {
182 p++;
183 char *end;
184 *val = strtoull(p, &end, 0);
185 return 0;
186 } else if (isdigit((unsigned char)*p)) {
187 char *end;
188 *val = strtoull(p, &end, 0);
189 return 0;
190 }
191 return -1;
192}
193
194static int cmd_audit_verify(int argc, char **argv) {
195 if (argc != 7) {
196 return fail("usage: %s <atlas.bin> <atlas.sha256> <atlas.manifest> <machine_contract.json> <atlas.audit> <atlas.decode>", argv[0]);
197 }
198 const char *p_bin = argv[1];
199 const char *p_sha = argv[2];
200 const char *p_manifest = argv[3];
201 const char *p_contract = argv[4];
202 const char *p_audit = argv[5];
203 const char *p_decode = argv[6];
204
205 printf("======================================================================\n");
206 printf("SEAM 1: INDEPENDENT ARTIFACT-AUDIT SEAM (ATLAS)\n");
207 printf("======================================================================\n\n");
208
209 /* 1. Identity Check */
210 printf("[Audit-1] Checking Canonical Artifact Identity...\n");
211 uint8_t *bin_buf; uint64_t bin_sz;
212 if (read_file(p_bin, &bin_buf, &bin_sz)) return 1;
213
214 uint8_t digest[32];
215 sha256_file_buf(bin_buf, bin_sz, digest);
216 char comp_hex[65];
217 sha256_to_hex(digest, comp_hex);
218
219 uint8_t *sha_buf; uint64_t sha_sz;
220 if (read_file(p_sha, &sha_buf, &sha_sz)) { free(bin_buf); return 1; }
221 char exp_hex[65];
222 if (sscanf((char *)sha_buf, "%64s", exp_hex) != 1) {
223 free(bin_buf); free(sha_buf);
224 return fail("invalid sha256 file format: %s", p_sha);
225 }
226 free(sha_buf);
227
228 printf(" atlas.bin size: %llu bytes\n", (unsigned long long)bin_sz);
229 printf(" Computed SHA-256: %s\n", comp_hex);
230 printf(" Recorded SHA-256: %s\n", exp_hex);
231
232 if (strcmp(comp_hex, exp_hex) != 0) {
233 printf(" -> ATLAS_ARTIFACT_IDENTITY_PASS: FAILED\n");
234 free(bin_buf);
235 return 1;
236 }
237 printf(" -> ATLAS_ARTIFACT_IDENTITY_PASS: OK\n\n");
238
239 /* 2. Machine Contract */
240 printf("[Audit-2] Validating Machine Contract Adherence...\n");
241 uint8_t *contract_buf; uint64_t contract_sz;
242 if (read_file(p_contract, &contract_buf, &contract_sz)) { free(bin_buf); return 1; }
243 uint8_t *manifest_buf; uint64_t manifest_sz;
244 if (read_file(p_manifest, &manifest_buf, &manifest_sz)) { free(bin_buf); free(contract_buf); return 1; }
245
246 uint64_t max_size = 65536;
247 json_extract_u64((char *)contract_buf, "atlas_max_size_bytes", &max_size);
248
249 char contract_id[128] = {0};
250 json_extract_str((char *)contract_buf, "contract_id", contract_id, sizeof(contract_id));
251
252 char target_platform[128] = {0};
253 json_extract_str((char *)contract_buf, "target_platform", target_platform, sizeof(target_platform));
254
255 char pinned_digest[128] = {0};
256 json_extract_str((char *)contract_buf, "pinned_digest_hex", pinned_digest, sizeof(pinned_digest));
257
258 char digest_algo[64] = {0};
259 json_extract_str((char *)contract_buf, "digest_algorithm", digest_algo, sizeof(digest_algo));
260
261 char manifest_sha[128] = {0};
262 json_extract_str((char *)manifest_buf, "sha256", manifest_sha, sizeof(manifest_sha));
263
264 char manifest_target[128] = {0};
265 json_extract_str((char *)manifest_buf, "target_physics_entry", manifest_target, sizeof(manifest_target));
266
267 char contract_target[128] = {0};
268 json_extract_str((char *)contract_buf, "physics_payload_base", contract_target, sizeof(contract_target));
269
270 int contract_ok = 1;
271 if (bin_sz > max_size) {
272 printf(" FAIL: Binary size exceeds contract ceiling (%llu > %llu)\n", (unsigned long long)bin_sz, (unsigned long long)max_size);
273 contract_ok = 0;
274 }
275 if (strcmp(manifest_sha, comp_hex) != 0) {
276 printf(" FAIL: Manifest sha256 mismatch\n");
277 contract_ok = 0;
278 }
279 if (strcasecmp(manifest_target, contract_target) != 0) {
280 printf(" FAIL: Target physics entry mismatch with contract (%s != %s)\n", manifest_target, contract_target);
281 contract_ok = 0;
282 }
283 if (strcmp(digest_algo, "sha256") != 0) {
284 printf(" FAIL: Machine contract must mandate cryptographic SHA-256 digest\n");
285 contract_ok = 0;
286 }
287
288 if (!contract_ok) {
289 printf(" -> ATLAS_MACHINE_CONTRACT_PASS: FAILED\n");
290 free(bin_buf); free(contract_buf); free(manifest_buf);
291 return 1;
292 }
293 printf(" Contract ID: %s\n", contract_id);
294 printf(" Target Platform: %s\n", target_platform);
295 printf(" Cryptographic Hash: SHA-256 (Pinned: %.16s...)\n", pinned_digest);
296 printf(" Max Size Bound: %llu bytes (Actual: %llu bytes)\n", (unsigned long long)max_size, (unsigned long long)bin_sz);
297 printf(" -> ATLAS_MACHINE_CONTRACT_PASS: OK\n\n");
298
299 /* 3. Exact Byte Accounting & Static Target Proof */
300 printf("[Audit-3] Verifying Exact Byte Accounting & Static Target Proof...\n");
301 uint8_t *audit_buf; uint64_t audit_sz;
302 if (read_file(p_audit, &audit_buf, &audit_sz)) { free(bin_buf); free(contract_buf); free(manifest_buf); return 1; }
303
304 uint64_t total_words = bin_sz / 4;
305 uint64_t audit_rows = 0;
306 uint64_t inst_count = 0;
307 uint64_t data_count = 0;
308 int audit_ok = 1;
309
310 char *saveptr;
311 char *line = strtok_r((char *)audit_buf, "\n", &saveptr);
312 while (line) {
313 if (strncmp(line, "| `0x", 5) == 0) {
314 audit_rows++;
315 if (strstr(line, "INSTRUCTION") != NULL) {
316 inst_count++;
317 if (strstr(line, "Write") != NULL) {
318 if (!strstr(line, "x20") && !strstr(line, "x22") && !strstr(line, "sp") &&
319 !strstr(line, "x2") && !strstr(line, "x1") && !strstr(line, "x3") &&
320 !strstr(line, "x4") && !strstr(line, "x12") && !strstr(line, "x0")) {
321 printf(" SECURITY WARNING: Unbounded write in audit row: %s\n", line);
322 audit_ok = 0;
323 }
324 } else if (strstr(line, "Read") != NULL) {
325 if (!strstr(line, "x0") && !strstr(line, "x1") && !strstr(line, "x2") &&
326 !strstr(line, "x3") && !strstr(line, "x21") && !strstr(line, "x4") &&
327 !strstr(line, "sp") && !strstr(line, "Literal") && !strstr(line, "w2")) {
328 printf(" SECURITY WARNING: Unbounded read in audit row: %s\n", line);
329 audit_ok = 0;
330 }
331 }
332 } else {
333 data_count++;
334 }
335 }
336 line = strtok_r(NULL, "\n", &saveptr);
337 }
338
339 printf(" Binary Size: %llu bytes\n", (unsigned long long)bin_sz);
340 printf(" Expected 32-bit Words: %llu\n", (unsigned long long)total_words);
341 printf(" Audit Ledger Entries: %llu\n", (unsigned long long)audit_rows);
342
343 if (audit_rows != total_words) {
344 printf(" FAIL: Audit entry count (%llu) != expected word count (%llu)\n",
345 (unsigned long long)audit_rows, (unsigned long long)total_words);
346 audit_ok = 0;
347 }
348
349 uint64_t reconciled = inst_count * 4 + data_count * 4;
350 printf(" Decoded Instructions: %llu (%llu bytes)\n", (unsigned long long)inst_count, (unsigned long long)(inst_count * 4));
351 printf(" Read-Only Data Words: %llu (%llu bytes)\n", (unsigned long long)data_count, (unsigned long long)(data_count * 4));
352 printf(" Reconciled Byte Sum: %llu bytes\n", (unsigned long long)reconciled);
353 printf(" Exact Discrepancy: %lld bytes (ZERO DELTA)\n", (long long)(bin_sz - reconciled));
354
355 if (reconciled != bin_sz) {
356 printf(" FAIL: Reconciled bytes (%llu) do not match file size (%llu)!\n",
357 (unsigned long long)reconciled, (unsigned long long)bin_sz);
358 audit_ok = 0;
359 }
360
361 /* Static Target Proof */
362 printf("\n[Audit-4] Evaluating Static Target Proof for Indirect Handoff ('br x19')...\n");
363 uint8_t *decode_buf; uint64_t decode_sz;
364 if (read_file(p_decode, &decode_buf, &decode_sz)) {
365 free(bin_buf); free(contract_buf); free(manifest_buf); free(audit_buf);
366 return 1;
367 }
368
369 /* Find "br\tx19" or "br x19" */
370 char *br_pos = strstr((char *)decode_buf, "br\tx19");
371 if (!br_pos) br_pos = strstr((char *)decode_buf, "br x19");
372
373 if (!br_pos) {
374 printf(" FAIL: Did not find 'br x19' handoff instruction in disassembly!\n");
375 audit_ok = 0;
376 } else {
377 /* Backtrack to beginning of line to find hex offset */
378 char *line_start = br_pos;
379 while (line_start > (char *)decode_buf && *(line_start - 1) != '\n') line_start--;
380 uint64_t br_offset = strtoull(line_start, NULL, 16);
381 uint64_t pred_offset = br_offset - 4;
382
383 /* Find predecessor line at pred_offset */
384 char pred_hex[32];
385 snprintf(pred_hex, sizeof(pred_hex), "\n %x:", (unsigned)pred_offset);
386 char *pred_pos = strstr((char *)decode_buf, pred_hex);
387 if (!pred_pos) {
388 snprintf(pred_hex, sizeof(pred_hex), "\n%x:", (unsigned)pred_offset);
389 pred_pos = strstr((char *)decode_buf, pred_hex);
390 }
391
392 if (!pred_pos || strstr(pred_pos, "ldr\tx19,") == NULL) {
393 printf(" FAIL: Predecessor instruction at 0x%04x is not 'ldr x19, <literal>'!\n", (unsigned)pred_offset);
394 audit_ok = 0;
395 } else {
396 char *lit_str = strstr(pred_pos, "ldr\tx19,");
397 lit_str += strlen("ldr\tx19,");
398 while (*lit_str == ' ' || *lit_str == '\t') lit_str++;
399 uint64_t literal_addr = 0;
400 if (!parse_literal(lit_str, &literal_addr) ||
401 literal_addr > bin_sz || bin_sz - literal_addr < 8) {
402 printf(" FAIL: Literal address 0x%llx is beyond binary size\n", (unsigned long long)literal_addr);
403 audit_ok = 0;
404 } else {
405 uint64_t target_val = 0;
406 for (int i = 0; i < 8; i++) target_val |= (uint64_t)bin_buf[literal_addr + i] << (8 * i);
407 uint64_t exp_target = 0x40200000;
408 json_extract_u64((char *)contract_buf, "physics_payload_base", &exp_target);
409
410 printf(" Handoff Branch Instruction: 0x%04x: br x19\n", (unsigned)br_offset);
411 printf(" Target Loader Instruction: 0x%04x: ldr x19, literal @ 0x%04x\n", (unsigned)pred_offset, (unsigned)literal_addr);
412 printf(" Static Literal Target Val: 0x%08llx\n", (unsigned long long)target_val);
413 printf(" Contract Physics Base: 0x%08llx\n", (unsigned long long)exp_target);
414
415 if (target_val == exp_target) {
416 printf(" -> STATIC TARGET PROOF VERIFIED: x19 is provably immutable 0x40200000.\n");
417 } else {
418 printf(" FAIL: Static target 0x%08llx != expected 0x%08llx!\n",
419 (unsigned long long)target_val, (unsigned long long)exp_target);
420 audit_ok = 0;
421 }
422 }
423 }
424 }
425
426 if (audit_ok) {
427 printf(" -> ATLAS_AUDIT_PASS: OK\n\n");
428 } else {
429 printf(" -> ATLAS_AUDIT_PASS: FAILED\n\n");
430 free(bin_buf); free(contract_buf); free(manifest_buf); free(audit_buf); free(decode_buf);
431 return 1;
432 }
433
434 /* 4. Disjoint Stack / Descriptor Proof */
435 printf("[Audit-5] Verifying Disjoint Stack / Boot-Descriptor Partition Proof...\n");
436 uint64_t stack_base = 0x401F0000;
437 uint64_t stack_top = 0x401FC000;
438 uint64_t desc_addr = 0x401FE000;
439 uint64_t desc_size = 64;
440 uint64_t contract_gap = 8192;
441
442 json_extract_u64((char *)contract_buf, "scratchpad_stack_base", &stack_base);
443 json_extract_u64((char *)contract_buf, "scratchpad_stack_top", &stack_top);
444 json_extract_u64((char *)contract_buf, "boot_descriptor_address", &desc_addr);
445 json_extract_u64((char *)contract_buf, "boot_descriptor_size_bytes", &desc_size);
446 json_extract_u64((char *)contract_buf, "guard_gap_size_bytes", &contract_gap);
447
448 uint64_t calc_gap = desc_addr - stack_top;
449 printf(" Stack Allocation Window: [0x%08llx, 0x%08llx) (downward growing)\n",
450 (unsigned long long)stack_base, (unsigned long long)stack_top);
451 printf(" Descriptor Allocation Window: [0x%08llx, 0x%08llx)\n",
452 (unsigned long long)desc_addr, (unsigned long long)(desc_addr + desc_size));
453 printf(" Calculated Guard Gap: %llu bytes (%llu KiB)\n",
454 (unsigned long long)calc_gap, (unsigned long long)(calc_gap / 1024));
455 printf(" Contract Stated Guard Gap: %llu bytes\n", (unsigned long long)contract_gap);
456
457 int disjoint_ok = 1;
458 if (calc_gap != contract_gap) {
459 printf(" FAIL: Calculated gap (%llu) != contract gap (%llu)\n",
460 (unsigned long long)calc_gap, (unsigned long long)contract_gap);
461 disjoint_ok = 0;
462 }
463 if (calc_gap < 4096) {
464 printf(" FAIL: Guard gap is insufficient (< 4 KiB)\n");
465 disjoint_ok = 0;
466 }
467 if (stack_top > desc_addr) {
468 printf(" FAIL: Stack top extends into/past descriptor!\n");
469 disjoint_ok = 0;
470 }
471
472 /* Verify SP initialization in decode */
473 char *sp_mov = strstr((char *)decode_buf, "mov\tsp, x0");
474 if (!sp_mov) sp_mov = strstr((char *)decode_buf, "mov sp, x0");
475
476 if (sp_mov) {
477 /* Backtrack to find preceding ldr x0 */
478 char *p_ldr = sp_mov;
479 while (p_ldr > (char *)decode_buf && strncmp(p_ldr, "ldr\tx0,", 7) != 0 && strncmp(p_ldr, "ldr x0,", 6) != 0) {
480 p_ldr--;
481 }
482 if (strncmp(p_ldr, "ldr\tx0,", 7) == 0 || strncmp(p_ldr, "ldr x0,", 6) == 0) {
483 char *lit_str = strchr(p_ldr, ',');
484 lit_str++;
485 while (*lit_str == ' ' || *lit_str == '\t') lit_str++;
486 uint64_t sp_lit_addr;
487 if (parse_literal(lit_str, &sp_lit_addr) &&
488 sp_lit_addr <= bin_sz && bin_sz - sp_lit_addr >= 8) {
489 uint64_t loaded_sp = 0;
490 for (int i = 0; i < 8; i++) loaded_sp |= (uint64_t)bin_buf[sp_lit_addr + i] << (8 * i);
491 printf(" Static SP Loader Value: 0x%08llx\n", (unsigned long long)loaded_sp);
492 if (loaded_sp == stack_top) {
493 printf(" -> SP setup matches contract scratchpad stack top exactly.\n");
494 } else {
495 printf(" FAIL: SP initialized to 0x%08llx, expected 0x%08llx!\n",
496 (unsigned long long)loaded_sp, (unsigned long long)stack_top);
497 disjoint_ok = 0;
498 }
499 } else {
500 printf(" FAIL: SP literal address out of bounds\n");
501 disjoint_ok = 0;
502 }
503 } else {
504 printf(" FAIL: Could not locate ldr x0 before mov sp, x0\n");
505 disjoint_ok = 0;
506 }
507 } else {
508 printf(" FAIL: Could not verify SP initialization sequence in decode!\n");
509 disjoint_ok = 0;
510 }
511
512 if (disjoint_ok) {
513 printf(" Formal Set Intersection: Stack Window ∩ Descriptor Window = ∅ (EMPTY_SET)\n");
514 printf(" -> ATLAS_STACK_DESCRIPTOR_DISJOINT_PASS: OK\n\n");
515 } else {
516 printf(" -> ATLAS_STACK_DESCRIPTOR_DISJOINT_PASS: FAILED\n\n");
517 free(bin_buf); free(contract_buf); free(manifest_buf); free(audit_buf); free(decode_buf);
518 return 1;
519 }
520
521 printf("----------------------------------------------------------------------\n");
522 printf("SEAM 1 RESULTS: ALL STATIC AUDIT GATES PASSED (ATLAS)\n");
523 printf("----------------------------------------------------------------------\n");
524
525 free(bin_buf); free(contract_buf); free(manifest_buf); free(audit_buf); free(decode_buf);
526 return 0;
527}
528
529/* -------------------------------------------------------------------------
530 * Audit Generation (replaces generate_audit_ledger.py)
531 * ------------------------------------------------------------------------- */
532
533static int cmd_gen_audit(int argc, char **argv) {
534 if (argc != 5) {
535 return fail("usage: %s <atlas.bin> <atlas.elf> <out.audit> <out.decode>", argv[0]);
536 }
537 const char *p_bin = argv[1];
538 const char *p_elf = argv[2];
539 const char *p_out_audit = argv[3];
540 const char *p_out_decode = argv[4];
541
542 /* Argument vectors keep untrusted artifact paths inert. */
543 int out = open(p_out_decode, O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0600);
544 if (out < 0) return fail("cannot open decode output %s", p_out_decode);
545 pid_t pid = fork();
546 if (pid < 0) { close(out); return fail("cannot fork objdump"); }
547 if (pid == 0) {
548 if (dup2(out, STDOUT_FILENO) < 0) _exit(127);
549 close(out);
550 execlp("aarch64-linux-gnu-objdump", "aarch64-linux-gnu-objdump",
551 "-d", "--", p_elf, (char *)NULL);
552 _exit(127);
553 }
554 close(out);
555 int status;
556 while (waitpid(pid, &status, 0) < 0) {
557 if (errno != EINTR) return fail("cannot wait for objdump");
558 }
559 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) return fail("objdump failed on %s", p_elf);
560
561 uint8_t *bin_buf; uint64_t bin_sz;
562 if (read_file(p_bin, &bin_buf, &bin_sz)) return 1;
563 if (bin_sz % 4 != 0) { free(bin_buf); return fail("bin size %llu not multiple of 4", (unsigned long long)bin_sz); }
564 uint64_t total_words = bin_sz / 4;
565
566 uint8_t *decode_buf; uint64_t decode_sz;
567 if (read_file(p_out_decode, &decode_buf, &decode_sz)) { free(bin_buf); return 1; }
568
569 /* Parse decoded instructions into a hash / table */
570 typedef struct {
571 uint64_t offset;
572 char hex[16];
573 char op[128];
574 } DecodedEntry;
575
576 DecodedEntry *entries = malloc(total_words * sizeof(DecodedEntry));
577 size_t num_entries = 0;
578
579 char *saveptr;
580 char *line = strtok_r((char *)decode_buf, "\n", &saveptr);
581 while (line) {
582 /* Line format: " ac: d61f0260 br x19" */
583 while (*line == ' ') line++;
584 char *colon = strchr(line, ':');
585 if (colon) {
586 *colon = '\0';
587 char *end;
588 uint64_t off = strtoull(line, &end, 16);
589 if (end != line && off < bin_sz) {
590 char *rest = colon + 1;
591 while (*rest == ' ' || *rest == '\t') rest++;
592 char hex[16] = {0};
593 int pos = 0;
594 while (isxdigit((unsigned char)*rest) && pos < 15) hex[pos++] = *rest++;
595 hex[pos] = '\0';
596 while (*rest == ' ' || *rest == '\t') rest++;
597 if (pos == 8 && num_entries < total_words) {
598 entries[num_entries].offset = off;
599 snprintf(entries[num_entries].hex, sizeof(entries[num_entries].hex), "%s", hex);
600 snprintf(entries[num_entries].op, sizeof(entries[num_entries].op), "%s", rest);
601 num_entries++;
602 }
603 }
604 }
605 line = strtok_r(NULL, "\n", &saveptr);
606 }
607
608 FILE *f_audit = fopen(p_out_audit, "w");
609 if (!f_audit) {
610 free(bin_buf); free(decode_buf); free(entries);
611 return fail("cannot open %s for writing", p_out_audit);
612 }
613
614 fprintf(f_audit, "# ATLAS MACHINE OPERATION AUDIT LEDGER\n");
615 fprintf(f_audit, "## Normative Mathematical Accounting: 100%% Byte Reconciliation\n");
616 fprintf(f_audit, "Formerly designated Alpha in early bootstrap drafting.\n\n");
617 fprintf(f_audit, "- **Binary Artifact:** `atlas.bin` (%llu bytes)\n", (unsigned long long)bin_sz);
618 fprintf(f_audit, "- **Total 32-bit Words:** %llu words\n\n", (unsigned long long)total_words);
619 fprintf(f_audit, "| Offset | Raw Bytes | Decoded Operation / Content | Inputs | Outputs | Branch Target | Memory Accessed | Classification |\n");
620 fprintf(f_audit, "| :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- |\n");
621
622 uint64_t inst_count = 0;
623 uint64_t data_count = 0;
624
625 for (uint64_t i = 0; i < total_words; i++) {
626 uint64_t offset = i * 4;
627
628 char raw_hex[16];
629 snprintf(raw_hex, sizeof(raw_hex), "%02x%02x%02x%02x",
630 bin_buf[offset + 3], bin_buf[offset + 2], bin_buf[offset + 1], bin_buf[offset + 0]);
631
632 /* Find if in decoded entries */
633 const DecodedEntry *match = NULL;
634 for (size_t j = 0; j < num_entries; j++) {
635 if (entries[j].offset == offset) {
636 match = &entries[j];
637 break;
638 }
639 }
640
641 if (match) {
642 inst_count++;
643 const char *op = match->op;
644 char inputs[256] = "-";
645 char outputs[128] = "-";
646 char branch[128] = "-";
647 char mem[128] = "-";
648
649 if (strstr(op, "msr") != NULL) {
650 strcpy(inputs, "#0xf");
651 strcpy(outputs, "DAIF");
652 } else if (strstr(op, "mov\tsp") != NULL || strstr(op, "mov sp") != NULL) {
653 strcpy(inputs, "x0");
654 strcpy(outputs, "SP");
655 } else if (strstr(op, "str") != NULL) {
656 /* parse register and bracketed target */
657 const char *brk_o = strchr(op, '[');
658 const char *brk_c = strchr(op, ']');
659 if (brk_o && brk_c && brk_c > brk_o) {
660 char reg[32] = {0};
661 const char *p = op + 3;
662 if (*p == 'b') p++;
663 while (*p == ' ' || *p == '\t') p++;
664 int k = 0;
665 while (*p && *p != ',' && *p != ' ' && k < 31) reg[k++] = *p++;
666 reg[k] = '\0';
667 if ((reg[0] == 'w' || reg[0] == 'x') && isdigit((unsigned char)reg[1])) {
668 snprintf(inputs, sizeof(inputs), "%s", reg);
669 char target[64] = {0};
670 size_t tlen = (size_t)(brk_c - brk_o + 1);
671 if (tlen < sizeof(target)) {
672 memcpy(target, brk_o, tlen);
673 target[tlen] = '\0';
674 snprintf(mem, sizeof(mem), "Write %s", target);
675 }
676 }
677 }
678 } else if (strstr(op, "ldr") != NULL) {
679 const char *brk_o = strchr(op, '[');
680 const char *brk_c = strchr(op, ']');
681 if (brk_o && brk_c && brk_c > brk_o) {
682 char reg[32] = {0};
683 const char *p = op + 3;
684 if (*p == 'b') p++;
685 while (*p == ' ' || *p == '\t') p++;
686 int k = 0;
687 while (*p && *p != ',' && *p != ' ' && k < 31) reg[k++] = *p++;
688 reg[k] = '\0';
689 snprintf(outputs, sizeof(outputs), "%s", reg);
690
691 char target[64] = {0};
692 size_t tlen = (size_t)(brk_c - brk_o + 1);
693 if (tlen < sizeof(target)) {
694 memcpy(target, brk_o, tlen);
695 target[tlen] = '\0';
696 snprintf(mem, sizeof(mem), "Read %s", target);
697 }
698 } else {
699 /* literal load: ldr x19, 160 */
700 char reg[32] = {0};
701 const char *comma = strchr(op, ',');
702 if (comma) {
703 const char *p = op + 3;
704 while (*p == ' ' || *p == '\t') p++;
705 int k = 0;
706 while (p < comma && k < 31) reg[k++] = *p++;
707 reg[k] = '\0';
708 snprintf(outputs, sizeof(outputs), "%s", reg);
709
710 const char *lit = comma + 1;
711 while (*lit == ' ' || *lit == '\t') lit++;
712 uint64_t lit_addr = strtoull(lit, NULL, 16);
713 snprintf(mem, sizeof(mem), "Literal @ 0x%04llx", (unsigned long long)lit_addr);
714 }
715 }
716 } else if (strstr(op, "bl\t") || strstr(op, "b\t") || strstr(op, "b.") || strstr(op, "cbz") || strstr(op, "br")) {
717 const char *last_space = strrchr(op, ' ');
718 const char *last_tab = strrchr(op, '\t');
719 const char *target = last_tab > last_space ? last_tab : last_space;
720 if (target) {
721 snprintf(branch, sizeof(branch), "%s", target + 1);
722 }
723 } else if (strstr(op, "adr") != NULL) {
724 char clean_op[256];
725 snprintf(clean_op, sizeof(clean_op), "%s", op);
726 for (size_t c = 0; clean_op[c]; c++) if (clean_op[c] == ',') clean_op[c] = ' ';
727 char p1[64], p2[64], p3[64];
728 if (sscanf(clean_op, "%63s %63s %63s", p1, p2, p3) == 3) {
729 snprintf(outputs, sizeof(outputs), "%s", p2);
730 snprintf(inputs, sizeof(inputs), "%s", p3);
731 }
732 } else if (strstr(op, "cmp") != NULL || strstr(op, "eor") != NULL || strstr(op, "mul") != NULL) {
733 char clean_op[256];
734 snprintf(clean_op, sizeof(clean_op), "%s", op);
735 for (size_t c = 0; clean_op[c]; c++) if (clean_op[c] == ',') clean_op[c] = ' ';
736 char *toks[16];
737 int n_tokens = 0;
738 char *sp_tok;
739 char *t = strtok_r(clean_op, " \t", &sp_tok);
740 while (t && n_tokens < 16) {
741 toks[n_tokens++] = t;
742 t = strtok_r(NULL, " \t", &sp_tok);
743 }
744 if (n_tokens >= 3) {
745 snprintf(outputs, sizeof(outputs), "%s", toks[1]);
746 inputs[0] = '\0';
747 size_t in_len = 0;
748 for (int k = 2; k < n_tokens; k++) {
749 in_len += snprintf(inputs + in_len, sizeof(inputs) - in_len, "%s%s",
750 (k == 2) ? "" : ", ", toks[k]);
751 }
752 }
753 }
754
755 fprintf(f_audit, "| `0x%04llx` | `%s` | `%s` | `%s` | `%s` | `%s` | `%s` | `%s` |\n",
756 (unsigned long long)offset, raw_hex, op, inputs, outputs, branch, mem, "INSTRUCTION");
757 } else {
758 data_count++;
759 fprintf(f_audit, "| `0x%04llx` | `%s` | `.word 0x%s` | `-` | `-` | `-` | `Read-Only Constant` | `%s` |\n",
760 (unsigned long long)offset, raw_hex, raw_hex, "RODATA / CONSTANT");
761 }
762 }
763
764 uint64_t reconciled = inst_count * 4 + data_count * 4;
765 fprintf(f_audit, "\n## Mathematical Reconciliation Summary\n");
766 fprintf(f_audit, "- Decoded Instructions: %llu (x 4 bytes = %llu bytes)\n",
767 (unsigned long long)inst_count, (unsigned long long)(inst_count * 4));
768 fprintf(f_audit, "- Read-Only Data Words: %llu (x 4 bytes = %llu bytes)\n",
769 (unsigned long long)data_count, (unsigned long long)(data_count * 4));
770 fprintf(f_audit, "- Reconciled Total: %llu bytes\n", (unsigned long long)reconciled);
771 fprintf(f_audit, "- Actual Binary File Size: %llu bytes\n", (unsigned long long)bin_sz);
772 fprintf(f_audit, "- Byte Discrepancy: %lld bytes (EXACT RECONCILIATION VERIFIED)\n",
773 (long long)(bin_sz - reconciled));
774
775 fclose(f_audit);
776 printf("Generated %s:\n", p_out_audit);
777 printf(" Instructions: %llu\n", (unsigned long long)inst_count);
778 printf(" Data Words: %llu\n", (unsigned long long)data_count);
779 printf(" Total Words: %llu (%llu bytes)\n", (unsigned long long)total_words, (unsigned long long)bin_sz);
780 printf(" Reconciliation: EXACT ZERO DELTA\n");
781
782 free(bin_buf); free(decode_buf); free(entries);
783 return 0;
784}
785
786/* -------------------------------------------------------------------------
787 * Mutation Generators
788 * ------------------------------------------------------------------------- */
789
790static int cmd_mutate_sweep(int argc, char **argv) {
791 if (argc != 4) return fail("usage: %s <in.bin> <offset> <out.bin>", argv[0]);
792 uint8_t *buf; uint64_t len, off;
793 if (parse_u64(argv[2], &off)) return 1;
794 if (read_file(argv[1], &buf, &len)) return 1;
795 if (off >= len) { free(buf); return fail("offset %llu >= len %llu", (unsigned long long)off, (unsigned long long)len); }
796 buf[off] ^= 0x01;
797 FILE *f = fopen(argv[3], "wb");
798 if (!f) { free(buf); return fail("cannot open %s for writing", argv[3]); }
799 fwrite(buf, 1, len, f);
800 fclose(f);
801 free(buf);
802 return 0;
803}
804
805static int cmd_mutate_adv(int argc, char **argv) {
806 if (argc != 4) return fail("usage: %s <in.bin> <scenario 0..11> <out.bin>", argv[0]);
807 uint64_t scn;
808 if (parse_u64(argv[2], &scn)) return 1;
809 if (scn > 11) return fail("scenario must be 0..11: %llu", (unsigned long long)scn);
810
811 uint8_t *buf; uint64_t len;
812 if (read_file(argv[1], &buf, &len)) return 1;
813 if (len < 256) { free(buf); return fail("payload len %llu < 256", (unsigned long long)len); }
814
815 switch (scn) {
816 case 0: buf[0] ^= 0x01; break;
817 case 1: buf[8] ^= 0xFF; break;
818 case 2: buf[24] ^= 0xAA; break;
819 case 3: buf[64] ^= 0x55; break;
820 case 4: buf[128] ^= 0x01; break;
821 case 5: buf[160] ^= 0x20; break;
822 case 6: buf[200] ^= 0x04; break;
823 case 7: buf[254] ^= 0x80; break;
824 case 8: buf[255] ^= 0x01; break;
825 case 9: for (int i = 40; i < 48; i++) buf[i] ^= 0xCC; break;
826 case 10: memset(buf, 0x00, len); break;
827 case 11: memset(buf, 0xFF, len); break;
828 }
829
830 FILE *f = fopen(argv[3], "wb");
831 if (!f) { free(buf); return fail("cannot open %s for writing", argv[3]); }
832 fwrite(buf, 1, len, f);
833 fclose(f);
834 free(buf);
835 return 0;
836}
837
838/* -------------------------------------------------------------------------
839 * Fast QEMU Execution Harness
840 * ------------------------------------------------------------------------- */
841
842static int run_qemu_proc(const char *atlas_bin, const char *physics_bin, int timeout_ms,
843 char *out_buf, size_t out_cap) {
844 int pfd[2];
845 if (pipe2(pfd, O_CLOEXEC) < 0) return -1;
846
847 pid_t pid = fork();
848 if (pid < 0) {
849 close(pfd[0]); close(pfd[1]);
850 return -1;
851 }
852
853 if (pid == 0) {
854 dup2(pfd[1], STDOUT_FILENO);
855 dup2(pfd[1], STDERR_FILENO);
856 char dev_arg[512];
857 snprintf(dev_arg, sizeof(dev_arg), "loader,file=%s,addr=0x40200000", physics_bin);
858 char *argv[] = {
859 "qemu-system-aarch64",
860 "-M", "virt",
861 "-cpu", "cortex-a57",
862 "-m", "128M",
863 "-nographic",
864 "-bios", (char *)atlas_bin,
865 "-device", dev_arg,
866 NULL
867 };
868 execvp("qemu-system-aarch64", argv);
869 _exit(127);
870 }
871
872 close(pfd[1]);
873 size_t total = 0;
874 out_buf[0] = '\0';
875
876 struct pollfd pfd_poll = { .fd = pfd[0], .events = POLLIN };
877 int remaining = timeout_ms;
878
879 while (remaining > 0) {
880 int r = poll(&pfd_poll, 1, 10);
881 if (r > 0 && (pfd_poll.revents & POLLIN)) {
882 char buf[512];
883 ssize_t n = read(pfd[0], buf, sizeof(buf) - 1);
884 if (n > 0) {
885 buf[n] = '\0';
886 if (total + n < out_cap - 1) {
887 memcpy(out_buf + total, buf, n);
888 total += n;
889 out_buf[total] = '\0';
890 }
891 if (strstr(out_buf, "PHYSICS-0: AUTHORIZED") != NULL ||
892 strstr(out_buf, "ATLAS: REFUSE") != NULL) {
893 break;
894 }
895 } else if (n == 0) {
896 break;
897 }
898 }
899 remaining -= 10;
900 }
901
902 kill(pid, SIGKILL);
903 int status;
904 waitpid(pid, &status, 0);
905 close(pfd[0]);
906
907 int has_refuse = (strstr(out_buf, "ATLAS: REFUSE") != NULL);
908 int has_auth = (strstr(out_buf, "PHYSICS-0: AUTHORIZED") != NULL);
909 int has_handoff = (strstr(out_buf, "ATLAS: HANDOFF") != NULL);
910
911 if (has_handoff && has_auth && !has_refuse) return 0;
912 if (has_refuse && !has_auth && !has_handoff) return 1;
913 return 2;
914}
915
916static int cmd_qemu_run(int argc, char **argv) {
917 if (argc < 3 || argc > 4) return fail("usage: %s <atlas.bin> <physics.bin> [timeout_ms]", argv[0]);
918 int timeout_ms = 1500;
919 if (argc == 4) timeout_ms = atoi(argv[3]);
920 if (timeout_ms <= 0) timeout_ms = 1500;
921
922 char out[4096];
923 int r = run_qemu_proc(argv[1], argv[2], timeout_ms, out, sizeof(out));
924 printf("%s", out);
925 return r;
926}
927
928static int cmd_qemu_matrix(int argc, char **argv) {
929 if (argc != 3) return fail("usage: %s <atlas.bin> <physics-0.bin>", argv[0]);
930 const char *atlas_bin = argv[1];
931 const char *physics_bin = argv[2];
932
933 printf("======================================================================\n");
934 printf("SEAM 2: EXTERNAL EXECUTION SEAM (QEMU AARCH64 VIRT - ATLAS)\n");
935 printf("======================================================================\n\n");
936
937 /* 1. Golden Boot */
938 printf("[Exec-1] Executing Clean Golden Boot & Handoff with Cryptographic SHA-256...\n");
939 char out_buf[4096];
940 int r = run_qemu_proc(atlas_bin, physics_bin, 2000, out_buf, sizeof(out_buf));
941 printf(" Emitted Telemetry Stream:\n");
942 char *saveptr;
943 char *line = strtok_r(out_buf, "\n", &saveptr);
944 while (line) {
945 printf(" | %s\n", line);
946 line = strtok_r(NULL, "\n", &saveptr);
947 }
948 if (r == 0) {
949 printf(" -> ATLAS_BOOT_QEMU_PASS: OK\n");
950 printf(" -> ATLAS_HANDOFF_QEMU_PASS: OK\n");
951 } else {
952 printf(" -> ATLAS_BOOT_QEMU_PASS: FAILED\n");
953 printf(" -> ATLAS_HANDOFF_QEMU_PASS: FAILED\n");
954 return 1;
955 }
956
957 /* 2A. 256-single-byte sweep */
958 uint8_t *golden_buf; uint64_t golden_sz;
959 if (read_file(physics_bin, &golden_buf, &golden_sz)) return 1;
960 if (golden_sz != 256) { free(golden_buf); return fail("golden payload size %llu != 256", (unsigned long long)golden_sz); }
961
962 printf("\n[Exec-2A] Executing Exhaustive 256-Single-Byte Mutation Sweep (Offsets 0..255)...\n");
963 char tmp_dir[] = "/tmp/atlas_sweep_XXXXXX";
964 if (!mkdtemp(tmp_dir)) { free(golden_buf); return fail("cannot create private sweep directory"); }
965 char tmp_path[sizeof(tmp_dir) + sizeof("/mutant.bin")];
966 snprintf(tmp_path, sizeof(tmp_path), "%s/mutant.bin", tmp_dir);
967 int tmp_fd = open(tmp_path, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, 0600);
968 if (tmp_fd < 0) { rmdir(tmp_dir); free(golden_buf); return fail("cannot create sweep file"); }
969
970 struct timespec t0, t1;
971 clock_gettime(CLOCK_MONOTONIC, &t0);
972
973 int sweep_ok = 1;
974 uint8_t mut_buf[256];
975
976 for (int offset = 0; offset < 256; offset++) {
977 memcpy(mut_buf, golden_buf, 256);
978 mut_buf[offset] ^= 0x01;
979
980 if (lseek(tmp_fd, 0, SEEK_SET) < 0 ||
981 write(tmp_fd, mut_buf, sizeof(mut_buf)) != (ssize_t)sizeof(mut_buf)) {
982 close(tmp_fd); unlink(tmp_path); rmdir(tmp_dir); free(golden_buf);
983 return fail("cannot write sweep file");
984 }
985
986 char out[1024];
987 int res = run_qemu_proc(atlas_bin, tmp_path, 1500, out, sizeof(out));
988 if (res != 1) {
989 printf(" FAIL at byte offset %d: result=%d output=%s\n", offset, res, out);
990 sweep_ok = 0;
991 break;
992 }
993
994 if ((offset + 1) % 64 == 0 || offset == 255) {
995 printf(" Tested %3d/256 byte offsets: all refused into quiescence cleanly.\n", offset + 1);
996 }
997 }
998 clock_gettime(CLOCK_MONOTONIC, &t1);
999 double elapsed_sweep = (t1.tv_sec - t0.tv_sec) + (t1.tv_nsec - t0.tv_nsec) / 1e9;
1000 printf(" Exhaustive 256-Offset Sweep completed in %.2fs (Result: %s)\n",
1001 elapsed_sweep, sweep_ok ? "PASS" : "FAIL");
1002
1003 if (!sweep_ok) {
1004 close(tmp_fd); unlink(tmp_path); rmdir(tmp_dir); free(golden_buf);
1005 return 1;
1006 }
1007
1008 /* 2B. 12 Adversarial Mutations */
1009 printf("\n[Exec-2B] Executing 12 Adversarial Structured Mutation Scenarios...\n");
1010 static const struct {
1011 const char *name;
1012 const char *desc;
1013 int scn;
1014 } ADV_SCN[] = {
1015 { "MUT_00_FIRST_BYTE", "0 ", 0 },
1016 { "MUT_01_COOKIE_BYTE", "8 ", 1 },
1017 { "MUT_02_EARLY_INSN", "24 ", 2 },
1018 { "MUT_03_MID_INSN", "64 ", 3 },
1019 { "MUT_04_LATE_INSN", "128 ", 4 },
1020 { "MUT_05_MSG_BYTE", "160 ", 5 },
1021 { "MUT_06_MSG_END", "200 ", 6 },
1022 { "MUT_07_PENULTIMATE", "254 ", 7 },
1023 { "MUT_08_FINAL_BYTE", "255 ", 8 },
1024 { "MUT_09_BURST_FLIP", "40-48 ", 9 },
1025 { "MUT_10_ALL_ZEROS", "ALL ", 10 },
1026 { "MUT_11_ALL_ONES", "ALL ", 11 }
1027 };
1028
1029 int adv_ok = 1;
1030 for (size_t i = 0; i < sizeof(ADV_SCN)/sizeof(ADV_SCN[0]); i++) {
1031 memcpy(mut_buf, golden_buf, 256);
1032 switch (ADV_SCN[i].scn) {
1033 case 0: mut_buf[0] ^= 0x01; break;
1034 case 1: mut_buf[8] ^= 0xFF; break;
1035 case 2: mut_buf[24] ^= 0xAA; break;
1036 case 3: mut_buf[64] ^= 0x55; break;
1037 case 4: mut_buf[128] ^= 0x01; break;
1038 case 5: mut_buf[160] ^= 0x20; break;
1039 case 6: mut_buf[200] ^= 0x04; break;
1040 case 7: mut_buf[254] ^= 0x80; break;
1041 case 8: mut_buf[255] ^= 0x01; break;
1042 case 9: for (int b = 40; b < 48; b++) mut_buf[b] ^= 0xCC; break;
1043 case 10: memset(mut_buf, 0x00, 256); break;
1044 case 11: memset(mut_buf, 0xFF, 256); break;
1045 }
1046
1047 if (lseek(tmp_fd, 0, SEEK_SET) < 0 ||
1048 write(tmp_fd, mut_buf, sizeof(mut_buf)) != (ssize_t)sizeof(mut_buf)) {
1049 close(tmp_fd); unlink(tmp_path); rmdir(tmp_dir); free(golden_buf);
1050 return fail("cannot write sweep file");
1051 }
1052
1053 char out[1024];
1054 int res = run_qemu_proc(atlas_bin, tmp_path, 1500, out, sizeof(out));
1055 if (res == 1) {
1056 printf(" [PASS] %-20s (offset %s) -> Refused cleanly, physics isolated.\n",
1057 ADV_SCN[i].name, ADV_SCN[i].desc);
1058 } else {
1059 printf(" [FAIL] %-20s -> Did not refuse as expected! res=%d output=%s\n",
1060 ADV_SCN[i].name, res, out);
1061 adv_ok = 0;
1062 }
1063 }
1064
1065 if (sweep_ok && adv_ok) {
1066 printf(" -> ATLAS_CORRUPTION_REFUSAL_QEMU_PASS: OK (268/268 total mutations refused: 256 sweep + 12 adversarial)\n");
1067 } else {
1068 printf(" -> ATLAS_CORRUPTION_REFUSAL_QEMU_PASS: FAILED\n");
1069 close(tmp_fd); unlink(tmp_path); rmdir(tmp_dir);
1070 free(golden_buf);
1071 return 1;
1072 }
1073
1074 /* 3. Fail-Closed Quiescence */
1075 printf("\n[Exec-3] Verifying Fail-Closed Quiescence...\n");
1076 memcpy(mut_buf, golden_buf, 256);
1077 mut_buf[10] ^= 0x01;
1078 if (lseek(tmp_fd, 0, SEEK_SET) < 0 ||
1079 write(tmp_fd, mut_buf, sizeof(mut_buf)) != (ssize_t)sizeof(mut_buf)) {
1080 close(tmp_fd); unlink(tmp_path); rmdir(tmp_dir); free(golden_buf);
1081 return fail("cannot write quiescence mutant");
1082 }
1083
1084 char q_out[2048];
1085 run_qemu_proc(atlas_bin, tmp_path, 1500, q_out, sizeof(q_out));
1086 close(tmp_fd);
1087 unlink(tmp_path);
1088 rmdir(tmp_dir);
1089 free(golden_buf);
1090
1091 /* Verify terminal line is "ATLAS: REFUSE" and exactly 3 lines emitted */
1092 int line_count = 0;
1093 char last_line[128] = {0};
1094 char *q_save;
1095 char *q_line = strtok_r(q_out, "\n", &q_save);
1096 while (q_line) {
1097 while (*q_line == ' ' || *q_line == '\t') q_line++;
1098 if (*q_line) {
1099 line_count++;
1100 strncpy(last_line, q_line, sizeof(last_line) - 1);
1101 }
1102 q_line = strtok_r(NULL, "\n", &q_save);
1103 }
1104
1105 if (strcmp(last_line, "ATLAS: REFUSE") == 0) {
1106 printf(" Quiescence confirmed: execution halted cleanly after REFUSE.\n");
1107 printf(" Emitted %d total lines; zero instruction overrun or crash.\n", line_count);
1108 printf(" -> ATLAS_FAIL_CLOSED_QEMU_PASS: OK\n\n");
1109 } else {
1110 printf(" FAIL: Expected terminal telemetry 'ATLAS: REFUSE', found: %s\n", last_line);
1111 printf(" -> ATLAS_FAIL_CLOSED_QEMU_PASS: FAILED\n\n");
1112 return 1;
1113 }
1114
1115 printf("----------------------------------------------------------------------\n");
1116 printf("SEAM 2 RESULTS: ALL EXECUTION GATES PASSED (ATLAS)\n");
1117 printf("----------------------------------------------------------------------\n");
1118 return 0;
1119}
1120
1121static const struct {
1122 const char *name;
1123 int (*fn)(int, char **);
1124 const char *help;
1125} CMDS[] = {
1126 { "sha256", cmd_sha256, "sha256 <file>" },
1127 { "hexfield", cmd_hexfield, "hexfield <file> <offset> <width 1|2|4|8>" },
1128 { "bytes", cmd_bytes, "bytes <file> <offset> <len>" },
1129 { "audit-verify", cmd_audit_verify, "audit-verify <bin> <sha> <manifest> <contract> <audit> <decode>" },
1130 { "gen-audit", cmd_gen_audit, "gen-audit <bin> <elf> <out.audit> <out.decode>" },
1131 { "mutate-sweep", cmd_mutate_sweep, "mutate-sweep <in> <offset> <out>" },
1132 { "mutate-adv", cmd_mutate_adv, "mutate-adv <in> <scenario> <out>" },
1133 { "qemu-run", cmd_qemu_run, "qemu-run <atlas.bin> <physics.bin> [timeout_ms]" },
1134 { "qemu-matrix", cmd_qemu_matrix, "qemu-matrix <atlas.bin> <physics-0.bin>" },
1135};
1136
1137int main(int argc, char **argv) {
1138 if (argc >= 2) {
1139 for (size_t i = 0; i < sizeof(CMDS) / sizeof(CMDS[0]); i++) {
1140 if (strcmp(argv[1], CMDS[i].name) == 0) {
1141 return CMDS[i].fn(argc - 1, argv + 1);
1142 }
1143 }
1144 }
1145 fprintf(stderr, "m1tool -- ATLAS Milestone 1 Host Tool (no Python)\nUsage:\n");
1146 for (size_t i = 0; i < sizeof(CMDS) / sizeof(CMDS[0]); i++) {
1147 fprintf(stderr, " m1tool %s\n", CMDS[i].help);
1148 }
1149 return 1;
1150}