diff --git a/.crumb b/.crumb index f3e51fe46..7a934d277 100644 --- a/.crumb +++ b/.crumb @@ -72,7 +72,7 @@ }, { "digest": "f765ad87fdddd9b47f690b07298c951a0f7e7675dc5de4ffe44e33a0c14b1986", - "last_commit": "a8a6a3d3c", + "last_commit": "d94a503f7", "name": "spec", "purpose": "Directory spec. Purpose not yet described by a human." }, @@ -84,26 +84,26 @@ }, { "digest": "5395ff8ff9afceebe8e453788f80a3064b831513cc4cb92fd55869115e06b874", - "last_commit": "a8a6a3d3c", + "last_commit": "dcccc0211", "name": "tests", "purpose": "Directory tests. Purpose not yet described by a human." }, { "digest": "308db0e6cf45c0a48f01f5f5f228450f191389de68006915b9ecf9c65b9a2e29", - "last_commit": "a8a6a3d3c", + "last_commit": "a50c3bd41", "name": "tools", "purpose": "Directory tools. Purpose not yet described by a human." } ], "children_root": "sha256:07bf1706dcffbad66c0353871ff67a6749055da03cee8d8ebdf9a4c91e36bddc", - "compiled_at": "2026-10-30T12:31:50Z", + "compiled_at": "2026-10-30T16:29:10Z", "compiler": "crumb-compile/1", - "digest": "sha256:904fca8c0e0cf3e3a5e5adb73393e01c7018b920bb542d289904240f70e400d6", + "digest": "sha256:b22288b89b7cb7c2e5fcd1dd08bfc3535241d62ae630b443a54ebf47e70bb827", "evidence_files": 12622, "evidence_root": "sha256:b1a08e2ce56e6feada0d8a31f06fbd7adee57adc1c1ad8dec220293ee5d439f9", - "files": 17849, - "generated_at_commit": "52a82f392fa513ebbc2d9d719a0f14c385289b06", - "source_tree": "sha256:75458da6553a0ee5ea2af95f46afb658e8a3f6e53cca6e3b4b9874035f78c2ed" + "files": 17856, + "generated_at_commit": "18111bbfedcb5c5b80760e91eda9ba7815a61d73", + "source_tree": "sha256:5b2972a55a3b56a36d6477d86d7792968083ba4b04e424898d4d72424907ee4b" }, "owner_lane": "", "provenance": { diff --git a/om/aarch64/README.md b/om/aarch64/README.md new file mode 100644 index 000000000..2825632f4 --- /dev/null +++ b/om/aarch64/README.md @@ -0,0 +1,192 @@ +# om/aarch64: the legacy AArch64 writer, decoder and validator in seeded Omega + +`aarch64.om` ports two C files of the product to seeded Omega (aien-dev/omega-mv#726, +aien-dev/aien-architecture-mv#300/#316): + +| C | what it does | Omega functions | +|---|---|---| +| `src/aarch64_encoder.c` (+ `aarch64_encoder.h`) | the 25 `aarch64_emit_*` writers: range checks, refusal, word formula, little-endian store | `a64addreg` … `a64subsreg` (one per emitter), `a64put` | +| `src/aarch64_decoder.c` (+ `aarch64_decoder.h`) | `aarch64_decode_instruction`, `aarch64_validate_code_buffer` | `a64decode`, `a64validate` | +| `src/aarch64_target.h` | `Aarch64Reg`, `Aarch64Cond`, `AARCH64_MAX_CODE_BYTES` | the same values (tables below) | + +The C is unchanged. This change adds the port and its parity evidence. Removing the C objects goes +through the omega-bridge native call ABI (omega-bridge #8) and is not part of it. + +## Where the task text and the files differ + +- There is no `aarch64_core.h`. The headers are `aarch64_encoder.h`, `aarch64_decoder.h` and + `aarch64_target.h`. +- The decoder file also holds `aarch64_validate_code_buffer`, which callers use (`omega_verify.c`, + `visor_realization.c`); it is ported too, with its `snprintf` messages byte for byte. +- The encoder has no error codes for bad fields. An out-of-range field makes the C print + `A64_LEGACY_FIELD_OUT_OF_RANGE =` on stderr and `abort()`. The only error + result is -1 for a full buffer. The port returns a refusal code instead (see ABI), and the parity + harness prints the C's exact stderr line from it. +- "Round trip encode→decode→encode identical" holds for 14 of the 25 emitters only. The C decoder + drops fields for the other 11: ADR returns only `rd`; LDR/STR return `sf rd rn` but no offset and do + not tell the unsigned-offset form from the post-index form; LDRB/STRB return `rd rn` only; SUBS + returns `sf rd rn rm` and does not tell the immediate form from the register form. For those 11 the + harness checks instead that the decode gives the expected op and every field it carries equals the + emitter input (mark `~`). + +## Enum and numbering tables (value-compatible with the C headers) + +`DecodedOp` (`out 0` of `a64decode`): 0 INVALID, 1 ADD, 2 SUB, 3 MUL, 4 AND, 5 ORR, 6 EOR, 7 MOVZ, +8 RET, 9 B, 10 B_COND, 11 CBZ, 12 CBNZ, 13 MOVK, 14 ADR, 15 LDR, 16 STR, 17 LDRB, 18 STRB, 19 SUBS. + +`Aarch64Cond`: 0 EQ, 1 NE, 2 CS, 3 CC, 4 MI, 5 PL, 6 VS, 7 VC, 8 HI, 9 LS, 10 GE, 11 LT, 12 GT, +13 LE, 14 AL; the emitter also accepts 15 (NV), as the C does (`CHECK_COND` is 0..15). + +`Aarch64Reg`: `REG_X0`..`REG_X30` = 0..30, `REG_XZR` = `REG_SP` = 31. `AARCH64_MAX_CODE_BYTES` = 4096. + +`DecodedInsn` as `out edit ulong 9`, in struct order: 0 `op`, 1 `sf`, 2 `rd`, 3 `rn`, 4 `rm`, +5 `imm16`, 6 `hw`, 7 `branch_imm`, 8 `cond`. + +Emitter form numbers (corpus and harness only; the order of `aarch64_encoder.h`): 1 add_reg, 2 sub_reg, +3 mul_reg, 4 and_reg, 5 orr_reg, 6 eor_reg, 7 mov_reg, 8 movz, 9 ret, 10 b, 11 b_cond, 12 cbz, 13 cbnz, +14 movk, 15 adr, 16 ldr_uoff, 17 str_uoff, 18 ldrb_uoff, 19 strb_uoff, 20 ldr_post, 21 str_post, +22 ldr_x_post, 23 str_x_post, 24 subs_imm, 25 subs_reg. + +## ABI (omega-bridge native call ABI v1) + +Every exported function has at most 6 parameters, each `ulong`/`long` or a fixed-length `view`/`edit` +array of `ulong`/`uchar`, and returns `long`. + +| C | Omega | result | +|---|---|---| +| `aarch64_emit_
(buf, &pos, max_len, fields…)` | `a64 fields…` (fields in C order, after `max_len`) | the 32-bit word (0..2^32-1), or refusal code `-(k+1)` | +| `emit_u32_le` (static) | `a64put b(edit uchar 4096) st(edit ulong 2: pos, max_len) w` | `w` itself when `w < 0` (nothing written), else -1 when `pos + 4 > max_len`, else 0 after the store and `pos += 4` | +| `aarch64_decode_instruction(insn, &d)` | `a64decode insn out(edit ulong 9)` | 0, or -1 with `out` all 0 | +| `aarch64_validate_code_buffer(code, len, msg, ml)` | `a64validate code(view uchar 4096) len msg(edit uchar 256) ml` | 0, or -1 with the C's message in `msg` (snprintf rules) | + +So `aarch64_emit_(buf, &pos, max_len, …)` is `a64put b st (a64 …)`. A refusal code names +the first field that fails, in the C's check order: `k` is the field's 1-based position among the +emitter's fields (for `add_reg`: sf 1, rd 2, rn 3, rm 4, so a bad `rn` gives -4). An adapter that keeps +the C behaviour prints `A64_LEGACY_FIELD_OUT_OF_RANGE aarch64_emit_ =` and aborts +on it; -1 stays "buffer full". Field names: the C parameter names (`rd rn rm rt uoff simm9 imm12 imm16 +shift imm19 imm21 imm26 cond`). + +`parity/unit.py aarch64.om NAME` cuts the function-mode unit for `NAME`. All 28 units compile with the +pinned omc in function mode; the pinned generator (`src/native.om` of omega-bridge `012860db`, sha256 +`2c2c53f6…3940`) accepts them and the C it writes compiles with `-Wall -Wextra -Werror`, exporting +`omega_a64addreg` … `omega_a64validate`. In a separate check (a /tmp driver, not in the tree) every +corpus stream was run through those generated bindings; the output was byte-identical to the C oracle's. + +## What the C does, and the port keeps + +- Each emitter checks its fields before it encodes (`CHECK_REG` 0..31, `CHECK_SIGNED`, `CHECK_UMAX`, + `CHECK_COND` 0..15, `CHECK_HW_SHIFT` shift a multiple of 16 up to 48 (sf) or 16, `CHECK_SCALED` uoff + a multiple of 8 (sf) or 4 with uoff/size ≤ 4095). The check comes before the buffer test, so a bad + field is refused even when the buffer is full. `mov_reg` checks `rd` and `rm` under its own name, then + emits `ORR rd, XZR, rm`. +- The decoder tests its patterns in a fixed order and stops at the first match. Its MUL test + (`0x7FE07C00`) ignores bit 15, so `MNEG` (MSUB with XZR) decodes as MUL; the logical/arithmetic tests + ignore the shift type and amount; `branch_imm` is the raw unsigned field, not sign-extended; RET sets + `rn = 30`. +- The validator: an empty buffer, a length that is not a multiple of 4 (`%zu`), the first word that + does not decode (`0x%08x`, offset `0x%zx`), or a last word that is not RET (`op %d`), each with the C's + exact text, truncated the way `snprintf` truncates (at most `ml - 1` bytes and a NUL; nothing for + `ml = 0`). + +## Parity + +Reproduce from a fresh clone (no C oracle needed; the oracle's output is recorded as sha256 in +`parity/expected.txt`): + +``` +OMEGA_OMC=/path/to/seed/out/omc [OMEGA_BRIDGE=/path/to/omega-bridge] sh om/aarch64/parity/run.sh +``` + +It prints `AARCH64-PARITY PASS` in about 20 s on the Spark. `parity/corpus.py` regenerates the corpus +deterministically (splitmix64, fixed seeds, 3,152,381 records, 55 MB, never committed). + +Oracle: `src/aarch64_encoder.c` (sha256 `b892312e…1a17`) and `src/aarch64_decoder.c` (`d9e4bf06…beac`) +at omega-mv `acb3f15c`, compiled with `gcc -std=gnu11 -Wall -Wextra -Werror -D_GNU_SOURCE -O2 -Isrc` +(the Makefile CFLAGS, gcc 13.3.0, aarch64). `.text` sha256: encoder `13296478…1a03`, decoder +`2d14fdbc…c52d`, the same bytes as the `make`-built objects of other worktrees with the same sources. +A /tmp driver (not committed) feeds each stream to these objects. It catches each refusal's `abort()` +by `SIGABRT` → `siglongjmp`, with stderr on a memfd, and the record is the captured stderr line. + +| stream | inputs | words | refusals | result | +|---|---|---|---|---| +| `add_reg` `sub_reg` `mul_reg` `and_reg` `orr_reg` `eor_reg` `subs_reg` (each) | 76,408: **all** sf × rd × rn × rm (65,536), every register field 32..255, 200 random, 10,000 in range | 75,536-75,538 | 870-872 | identical | +| `mov_reg` | 12,696: all sf × rd × rm, rd/rm 32..255, 200 random, 10,000 in range | 12,051 | 645 | identical | +| `movz` `movk` (each) | 216,608: **all** sf × rd(0..255) × shift(0..255), **all** imm16, 10,000 random over the types, 10,000 in range | 75,747 / 75,744 | 140,861 / 140,864 | identical | +| `ret` | 1 | 1 | 0 | identical | +| `b` | 54,585: edges, every imm26 within 4096 of -2^25, 0, 2^25-1, 10,000 random in range, 10,000 over int32, 10,000 in range | 36,559 | 18,026 | identical | +| `b_cond` | 47,183: cond -3..19, 255, 256, int32 ends × imm19 edges, every cond 0..15 × imm19 -512..512, random | 36,674 | 10,509 | identical | +| `cbz` `cbnz` (each) | 44,848: sf × rt(0..255) × imm19 edges, random | 21,088 | 23,760 | identical | +| `adr` | 45,617: rd(0..255) × imm21 edges, imm21 -4096..4096, random | 28,737 | 16,880 | identical | +| `ldr_uoff` `str_uoff` (each) | 206,608: **all** sf × uoff(0..65535), rt × rn(0..255), 10,000 in range | 19,216 | 187,392 | identical | +| `ldrb_uoff` `strb_uoff` (each) | 141,072: **all** uoff, rt × rn(0..255), 10,000 in range | 14,866 / 14,886 | 126,206 / 126,186 | identical | +| `ldr_post` `str_post` `ldr_x_post` `str_x_post` (each) | 141,072: **all** simm9 over int16, rt × rn(0..255), 10,000 in range | 11,282-11,304 | 129,768-129,790 | identical | +| `subs_imm` | 206,608: **all** sf × imm12(0..65535), rd × rn(0..255), 10,000 in range | 19,216 | 187,392 | identical | +| `buf` | 3,201 sequences (50,436 emitter calls) into one buffer: max_len 0..40 × pos 0..max_len+8, edge fits at 4092..4096, max_len 2^63 and 2^64-1, 2,000 random | 25,130 stored, 25,306 buffer full | — | identical (every result, final pos, every byte) | +| `dec` | 462,893 words: 200,000 random; **all** 2^17 values of the 17 bits the decoder tests (mask `0xFFE07C10`), twice each with random other bits; RET and its 32 one-bit flips; each pattern, its full fill and its 32 one-bit flips | — | — | identical (44,410 decode, 418,483 invalid) | +| `val` | 2,181 buffers: every message at ml 0..100, 128, 255, 256; lengths 1..2^64-1 not a multiple of 4; every op as the last word; huge lengths stopped by a bad first word; 1,500 random programs of 1..1024 words | — | — | identical (801 valid, 1,380 refused, msg bytes 0..99) | + +Every encoder record also decodes the word it wrote. Round trip over the 969,015 words: 732,171 +re-encode from the decoded fields to the same word (the 14 forms whose decode carries every field), +236,844 decode to the expected op with every carried field equal (the 11 lossy forms), 0 wrong. + +GNU `as` (2.42, the Spark's `/usr/bin/as`) cross-check, run by `run.sh` when `as` is there: up to 200 +words per form, 4,801 in total over all 25 forms, are written back as assembly text from their fields +and assembled. Every word is identical to the .om's. + +Twenty-three mutants of `aarch64.om` are part of the verdict. Each must change its stream's hash: + +| mutant | records that change | +|---|---| +| add_reg opcode → AND's | add_reg 75,536 | +| rd accepted up to 32 | add_reg 1 | +| mov_reg reports `rm` as field 2 | mov_reg 242 | +| movz sf=1 shift limit 32 | movz 17,673 | +| movk hw at bit 22 | movk 55,578 | +| b accepts imm26 = 2^25 | b 1 | +| b.cond refuses cond 15 | b_cond 2,780 | +| cbz sf at bit 30 | cbz 10,597 | +| adr immlo at bit 28 | adr 21,483 | +| ldr uoff/size up to 4096 | ldr_uoff 2 | +| ldrb uoff up to 4096 | ldrb_uoff 1 | +| post-index simm9 mask 0xFF | ldr_post 5,625 | +| subs_imm sf=1 base 0xEB000000 | subs_imm 9,591 | +| buffer full at `pos + 4 >= max_len` | buf 146 | +| byte 0 of the store wrong | buf 1,742 | +| MUL test includes bit 15 | dec 8 | +| RET `rn` 0 | dec 1 | +| post-index LDR `sf` from bit 31 | dec 140 | +| b.cond `branch_imm` from bit 4 | dec 957 | +| `%08x` as `%07x` | val 82 | +| snprintf keeps `ml` bytes | val 430 | +| RET test on the second-last word | val 1,115 | +| decimal digit off by one | val 659 | + +## Limits + +- **Parameter types.** A value outside the C parameter's type traps 5: `sf` above 1 (bool), a + register or shift above 255 (`uint8_t`), imm16/uoff/imm12 above 65535 (`uint16_t`), simm9 outside + int16, imm19/imm21/imm26/cond outside int32, a decoded word above 2^32-1. The C cannot receive these + values; it narrows them at the call. +- **Refusal.** The port does not print or abort. It returns `-(k+1)`; printing the line and aborting is + the adapter's job (the harness does the printing). +- **Fixed arrays (ABI v1).** `a64put` stores into a 4096-byte buffer (`AARCH64_MAX_CODE_BYTES`). If a store + would go past it (`max_len` above 4096, or `pos + 4` wrapping), the first byte at index 4096 or beyond + traps 3. The C would write out of bounds there. Bytes below 4096 are written before the trap. Callers with smaller C buffers (128, 512, 1024) or + larger ones need an adapter that copies; it is not written here. `a64validate` reads at most 4096 + bytes of code: a length over 4096 whose first 1024 words all decode traps 3, where the C would read + past its caller's buffer (the product callers check `code_len <= 4096` first). Its `msg` is 256 bytes; + `ml` above 256 traps 3 before anything happens. With `ml = SIZE_MAX` the C's glibc `snprintf` drops + the message's last byte (end pointer wrap, depends on the buffer address), so `ml` above 256 is outside the contract. +- **NULL.** `out_dec == NULL` (C returns -1), `code == NULL` and a NULL `err_msg` cannot be expressed; + the adapter keeps those checks. +- **Lossy decode.** The round trip is a word identity only where the C's decode carries every field + (see above). + +## NOT_RUN + +- No GPU, model or serving test: this is host code. +- No `make test`/`make test-compiler`: the C files and every C caller are unchanged + (`tests/compiler/legacy_a64_allowlist.txt` is untouched). +- The C adapters, and the removal of `aarch64_encoder.o`/`aarch64_decoder.o` through omega-bridge #8, + are not done here. +- Only the pinned omc on Linux arm64 (the Spark) was used. diff --git a/om/aarch64/aarch64.om b/om/aarch64/aarch64.om new file mode 100644 index 000000000..2cde22d89 --- /dev/null +++ b/om/aarch64/aarch64.om @@ -0,0 +1,1215 @@ +note SPDX-License-Identifier: Apache-2.0 +note aarch64.om: seeded Omega port of src/aarch64_encoder.c (the legacy AArch64 instruction writer) +note and src/aarch64_decoder.c (its decoder and code-buffer validator), with the enum numbering of +note src/aarch64_target.h and src/aarch64_decoder.h (aien-dev/omega-mv#726). Same words, same +note decode fields, same refusals, same validator messages as the C built with the Makefile CFLAGS. +note +note Exported functions (omega-bridge native call ABI v1: ulong/long scalars, fixed-length +note ulong/uchar arrays, long result). Each a64 returns the 32-bit instruction word the +note matching aarch64_emit_ writes, or a refusal code where the C prints +note A64_LEGACY_FIELD_OUT_OF_RANGE and aborts: -(k+1) when field k (1-based, in the C parameter order +note after max_len) is out of its architectural range, the first such field in the C's check order. +note a64put b st w is the C's emit_u32_le: a refusal code passes through unwritten, else -1 when +note st 0 + 4 > st 1 (pos, max_len), else the word goes little-endian to b at st 0, st 0 += 4, 0. +note So aarch64_emit_(buf, &pos, max_len, fields) = a64put b st a64 fields. +note a64addreg sf rd rn rm a64subreg a64mulreg a64andreg a64orrreg a64eorreg (same fields) +note a64movreg sf rd rm a64movz sf rd imm16 shift a64movk sf rd imm16 shift +note a64ret a64b imm26 a64bcond cond imm19 +note a64cbz sf rt imm19 a64cbnz sf rt imm19 a64adr rd imm21 +note a64ldruoff sf rt rn uoff a64struoff sf rt rn uoff a64ldrbuoff rt rn uoff a64strbuoff rt rn uoff +note a64ldrpost rt rn simm9 a64strpost a64ldrxpost a64strxpost (same fields) +note a64subsimm sf rd rn imm12 a64subsreg sf rd rn rm +note a64put b st w b edit uchar 4096 (AARCH64_MAX_CODE_BYTES), st edit ulong 2 +note a64decode insn out aarch64_decode_instruction; out edit ulong 9 = DecodedInsn cells +note op sf rd rn rm imm16 hw branch_imm cond; returns 0 or -1 +note a64validate code n msg ml aarch64_validate_code_buffer; code view uchar 4096, msg edit uchar 256 +note A value outside the C parameter's type (bool sf, uint8_t register or shift, uint16_t imm16/uoff/ +note imm12, int16_t simm9, int32_t immediates and cond) traps 5: the C cannot receive it. + +note ---- conversions the C does by parameter type: trap 5 where the value does not fit ---- + +fn nbool v ulong to void +if gt v 1 +trap 5 +end +end + +fn nu8 v ulong to void +if gt v 255 +trap 5 +end +end + +fn nu16 v ulong to void +if gt v 65535 +trap 5 +end +end + +fn ni16 v long to void +if or lt v -32768 gt v 32767 +trap 5 +end +end + +fn ni32 v long to void +if or lt v -2147483648 gt v 2147483647 +trap 5 +end +end + +note ---- encoder: src/aarch64_encoder.c ---- + +note base | sf<<31 | rm<<16 | rn<<5 | rd, after CHECK3(rd, rn, rm); fields sf rd rn rm = 1 2 3 4 +fn a64rrr base ulong sf ulong rd ulong rn ulong rm ulong to long +nbool sf +nu8 rd +nu8 rn +nu8 rm +if gt rd 31 +ret -3 +end +if gt rn 31 +ret -4 +end +if gt rm 31 +ret -5 +end +w = or base shl sf 31 +w = or w shl rm 16 +w = or w shl rn 5 +ret long or w rd +end + +note 0x0B000000 +fn a64addreg sf ulong rd ulong rn ulong rm ulong to long +ret a64rrr 184549376 sf rd rn rm +end + +note 1<<30 | 0x0B000000 +fn a64subreg sf ulong rd ulong rn ulong rm ulong to long +ret a64rrr 1258291200 sf rd rn rm +end + +note MADD Xd, Xn, Xm, XZR: 0x1B000000 | 0x1f<<10 +fn a64mulreg sf ulong rd ulong rn ulong rm ulong to long +ret a64rrr 453016576 sf rd rn rm +end + +note 0x0A000000 +fn a64andreg sf ulong rd ulong rn ulong rm ulong to long +ret a64rrr 167772160 sf rd rn rm +end + +note 0x2A000000 +fn a64orrreg sf ulong rd ulong rn ulong rm ulong to long +ret a64rrr 704643072 sf rd rn rm +end + +note 0x4A000000 +fn a64eorreg sf ulong rd ulong rn ulong rm ulong to long +ret a64rrr 1241513984 sf rd rn rm +end + +note ORR rd, XZR, rm after its own CHECK_REG(rd), CHECK_REG(rm); fields sf rd rm = 1 2 3 +fn a64movreg sf ulong rd ulong rm ulong to long +nbool sf +nu8 rd +nu8 rm +if gt rd 31 +ret -3 +end +if gt rm 31 +ret -4 +end +ret a64orrreg sf rd 31 rm +end + +note MOVZ/MOVK: base | sf<<31 | (shift/16 & 3)<<21 | imm16<<5 | rd; fields sf rd imm16 shift = 1 2 3 4 +fn a64hw base ulong sf ulong rd ulong imm ulong sh ulong to long +nbool sf +nu8 rd +nu16 imm +nu8 sh +if gt rd 31 +ret -3 +end +mx = ulong 16 +if eq sf 1 +mx = 48 +end +if or ne rem sh 16 0 gt sh mx +ret -5 +end +w = or base shl sf 31 +w = or w shl and div sh 16 3 21 +w = or w shl imm 5 +ret long or w rd +end + +note 0x52800000 +fn a64movz sf ulong rd ulong imm ulong sh ulong to long +ret a64hw 1384120320 sf rd imm sh +end + +note 0x72800000 +fn a64movk sf ulong rd ulong imm ulong sh ulong to long +ret a64hw 1920991232 sf rd imm sh +end + +note 0xD65F03C0 +fn a64ret to long +ret 3596551104 +end + +note 0x14000000 | imm26 & 0x03FFFFFF; imm26 in [-2^25, 2^25) is field 1 +fn a64b imm long to long +ni32 imm +if or lt imm -33554432 ge imm 33554432 +ret -2 +end +ret long or 335544320 and bitcast ulong imm 67108863 +end + +note 0x54000000 | (imm19 & 0x7FFFF)<<5 | cond; cond 0..15 field 1, imm19 field 2 +fn a64bcond cond long imm long to long +ni32 cond +ni32 imm +if or lt cond 0 gt cond 15 +ret -2 +end +if or lt imm -262144 ge imm 262144 +ret -3 +end +w = shl and bitcast ulong imm 524287 5 +ret long or or 1409286144 w bitcast ulong cond +end + +note CBZ/CBNZ: base | sf<<31 | (imm19 & 0x7FFFF)<<5 | rt; fields sf rt imm19 = 1 2 3 +fn a64cbx base ulong sf ulong rt ulong imm long to long +nbool sf +nu8 rt +ni32 imm +if gt rt 31 +ret -3 +end +if or lt imm -262144 ge imm 262144 +ret -4 +end +w = or base shl sf 31 +w = or w shl and bitcast ulong imm 524287 5 +ret long or w rt +end + +note 0x34000000 +fn a64cbz sf ulong rt ulong imm long to long +ret a64cbx 872415232 sf rt imm +end + +note 0x35000000 +fn a64cbnz sf ulong rt ulong imm long to long +ret a64cbx 889192448 sf rt imm +end + +note 0x10000000 | (imm21 & 3)<<29 | ((imm21 >> 2) & 0x7FFFF)<<5 | rd; fields rd imm21 = 1 2 +fn a64adr rd ulong imm long to long +nu8 rd +ni32 imm +if gt rd 31 +ret -2 +end +if or lt imm -1048576 ge imm 1048576 +ret -3 +end +x = and bitcast ulong imm 2097151 +w = or 268435456 shl and x 3 29 +w = or w shl shr x 2 5 +ret long or w rd +end + +note LDR/STR (unsigned offset): (sf ? bx : bw) | (uoff >> (sf ? 3 : 2))<<10 | rn<<5 | rt; +note CHECK_SCALED: uoff a multiple of 8 (sf) or 4 with uoff/size <= 4095; fields sf rt rn uoff = 1 2 3 4 +fn a64ls bx ulong bw ulong sf ulong rt ulong rn ulong uo ulong to long +nbool sf +nu8 rt +nu8 rn +nu16 uo +if gt rt 31 +ret -3 +end +if gt rn 31 +ret -4 +end +sc = ulong 2 +sz = ulong 4 +base = bw +if eq sf 1 +sc = 3 +sz = 8 +base = bx +end +if or ne rem uo sz 0 gt div uo sz 4095 +ret -5 +end +w = or base shl and shr uo sc 4095 10 +w = or w shl rn 5 +ret long or w rt +end + +note 0xF9400000 / 0xB9400000 +fn a64ldruoff sf ulong rt ulong rn ulong uo ulong to long +ret a64ls 4181721088 3107979264 sf rt rn uo +end + +note 0xF9000000 / 0xB9000000 +fn a64struoff sf ulong rt ulong rn ulong uo ulong to long +ret a64ls 4177526784 3103784960 sf rt rn uo +end + +note LDRB/STRB (unsigned offset): base | uoff<<10 | rn<<5 | rt; uoff 0..4095; fields rt rn uoff = 1 2 3 +fn a64lsb base ulong rt ulong rn ulong uo ulong to long +nu8 rt +nu8 rn +nu16 uo +if gt rt 31 +ret -2 +end +if gt rn 31 +ret -3 +end +if gt uo 4095 +ret -4 +end +w = or base shl uo 10 +w = or w shl rn 5 +ret long or w rt +end + +note 0x39400000 +fn a64ldrbuoff rt ulong rn ulong uo ulong to long +ret a64lsb 960495616 rt rn uo +end + +note 0x39000000 +fn a64strbuoff rt ulong rn ulong uo ulong to long +ret a64lsb 956301312 rt rn uo +end + +note post-index: base | (simm9 & 0x1FF)<<12 | rn<<5 | rt; simm9 in [-256, 255]; fields rt rn simm9 = 1 2 3 +fn a64post base ulong rt ulong rn ulong imm long to long +nu8 rt +nu8 rn +ni16 imm +if gt rt 31 +ret -2 +end +if gt rn 31 +ret -3 +end +if or lt imm -256 ge imm 256 +ret -4 +end +w = or base shl and bitcast ulong imm 511 12 +w = or w shl rn 5 +ret long or w rt +end + +note 0xB8400400 +fn a64ldrpost rt ulong rn ulong imm long to long +ret a64post 3091203072 rt rn imm +end + +note 0xB8000400 +fn a64strpost rt ulong rn ulong imm long to long +ret a64post 3087008768 rt rn imm +end + +note 0xF8400400 +fn a64ldrxpost rt ulong rn ulong imm long to long +ret a64post 4164944896 rt rn imm +end + +note 0xF8000400 +fn a64strxpost rt ulong rn ulong imm long to long +ret a64post 4160750592 rt rn imm +end + +note SUBS (immediate): (sf ? 0xF1000000 : 0x71000000) | imm12<<10 | rn<<5 | rd; fields sf rd rn imm12 = 1 2 3 4 +fn a64subsimm sf ulong rd ulong rn ulong imm ulong to long +nbool sf +nu8 rd +nu8 rn +nu16 imm +if gt rd 31 +ret -3 +end +if gt rn 31 +ret -4 +end +if gt imm 4095 +ret -5 +end +base = ulong 1895825408 +if eq sf 1 +base = 4043309056 +end +w = or base shl imm 10 +w = or w shl rn 5 +ret long or w rd +end + +note SUBS (shifted register): (sf ? 0xEB000000 : 0x6B000000) | rm<<16 | rn<<5 | rd, which is +note 0x6B000000 | sf<<31 | ... +fn a64subsreg sf ulong rd ulong rn ulong rm ulong to long +ret a64rrr 1795162112 sf rd rn rm +end + +note emit_u32_le over a 4096-byte buffer; st 0 = *pos, st 1 = max_len. Where the C would write past +note a 4096-byte buffer (max_len above 4096, or pos + 4 wrapping), the first byte at index 4096 or +note beyond traps 3; the bytes below 4096 are already written. +fn a64put b edit uchar 4096 st edit ulong 2 w long to long +if lt w 0 +ret w +end +x = ulong uint w +p = get st 0 +if gt add p 4 get st 1 +ret -1 +end +put b p uchar and x 255 +put b add p 1 uchar and shr x 8 255 +put b add p 2 uchar and shr x 16 255 +put b add p 3 uchar shr x 24 +put st 0 add p 4 +ret 0 +end + +note ---- decoder: src/aarch64_decoder.c ---- + +note op; sf = bit sb of insn unless sb is 32; rd; rn when n >= 2; rm when n >= 3 +fn dregs out edit ulong 9 op ulong insn ulong sb ulong n ulong to void +put out 0 op +if lt sb 32 +put out 1 and shr insn sb 1 +end +put out 2 and insn 31 +if ge n 2 +put out 3 and shr insn 5 31 +end +if ge n 3 +put out 4 and shr insn 16 31 +end +end + +note MOVZ/MOVK fields +fn dwide out edit ulong 9 op ulong insn ulong to void +dregs out op insn 31 1 +put out 5 and shr insn 5 65535 +put out 6 and shr insn 21 3 +end + +note the checks of aarch64_decode_instruction 1-9 (RET .. SUB); 0 matched, 1 not +fn dec1 insn ulong out edit ulong 9 to ulong +if eq insn 3596551104 +put out 0 8 +put out 3 30 +ret 0 +end +if eq and insn 4227858432 335544320 +put out 0 9 +put out 7 and insn 67108863 +ret 0 +end +if eq and insn 4278190096 1409286144 +put out 0 10 +put out 8 and insn 15 +put out 7 and shr insn 5 524287 +ret 0 +end +m = and insn 2130706432 +if eq m 872415232 +dregs out 11 insn 31 1 +put out 7 and shr insn 5 524287 +ret 0 +end +if eq m 889192448 +dregs out 12 insn 31 1 +put out 7 and shr insn 5 524287 +ret 0 +end +if eq and insn 2139095040 1384120320 +dwide out 7 insn +ret 0 +end +if eq and insn 2145418240 453016576 +dregs out 3 insn 31 3 +ret 0 +end +m = and insn 2132803584 +if eq m 167772160 +dregs out 4 insn 31 3 +ret 0 +end +if eq m 704643072 +dregs out 5 insn 31 3 +ret 0 +end +if eq m 1241513984 +dregs out 6 insn 31 3 +ret 0 +end +if eq m 184549376 +dregs out 1 insn 31 3 +ret 0 +end +if eq m 1258291200 +dregs out 2 insn 31 3 +ret 0 +end +ret 1 +end + +note the checks 10-15 (MOVK .. SUBS); 0 matched, 1 not +fn dec2 insn ulong out edit ulong 9 to ulong +if eq and insn 2139095040 1920991232 +dwide out 13 insn +ret 0 +end +if eq and insn 2667577344 268435456 +dregs out 14 insn 32 1 +ret 0 +end +m = and insn 3208642560 +if eq m 3107979264 +dregs out 15 insn 30 2 +ret 0 +end +if eq m 3103784960 +dregs out 16 insn 30 2 +ret 0 +end +m = and insn 3219129344 +if eq m 3091203072 +dregs out 15 insn 30 2 +ret 0 +end +if eq m 3087008768 +dregs out 16 insn 30 2 +ret 0 +end +m = and insn 4290772992 +if eq m 960495616 +dregs out 17 insn 32 2 +ret 0 +end +if eq m 956301312 +dregs out 18 insn 32 2 +ret 0 +end +if eq and insn 2139095040 1895825408 +dregs out 19 insn 31 2 +ret 0 +end +if eq and insn 2132803584 1795162112 +dregs out 19 insn 31 3 +ret 0 +end +ret 1 +end + +note aarch64_decode_instruction: out = DecodedInsn (op sf rd rn rm imm16 hw branch_imm cond), all +note zero first; 0, or -1 with op 0 (DECODED_INVALID). branch_imm is the raw field, not sign-extended. +fn a64decode insn ulong out edit ulong 9 to long +nu32 insn +for i ulong 9 +put out i 0 +end +if eq dec1 insn out 0 +ret 0 +end +if eq dec2 insn out 0 +ret 0 +end +put out 0 0 +ret -1 +end + +fn nu32 v ulong to void +if gt v 4294967295 +trap 5 +end +end + +note ---- validator: aarch64_validate_code_buffer and its snprintf messages ---- + +note append the c low bytes of v (little-endian) to t at n; the new length +fn app t edit uchar 128 n ulong v ulong c ulong to ulong +for i ulong c +put t add n i uchar and shr v mul i 8 255 +end +ret add n c +end + +fn hexch v ulong to ulong +if lt v 10 +ret add v 48 +end +ret add v 87 +end + +note %x of v with at least w digits (w >= 1): %08x is w 8, %zx is w 1 +fn apphex t edit uchar 128 n ulong v ulong w ulong to ulong +k = ulong 1 +while lt k 16 bound 16 +if eq shr v mul k 4 0 +break +end +k = add k 1 +end +if lt k w +k = w +end +for i ulong k +put t add n i uchar hexch and shr v mul sub sub k 1 i 4 15 +end +ret add n k +end + +note %zu / %d (nonnegative) of v +fn appdec t edit uchar 128 n ulong v ulong to ulong +k = ulong 1 +q = div v 10 +while gt q 0 bound 20 +k = add k 1 +q = div q 10 +end +q = v +for i ulong k +put t add n sub sub k 1 i uchar add 48 rem q 10 +q = div q 10 +end +ret add n k +end + +note snprintf(msg, ml, ...) of the n bytes in t: at most ml - 1 bytes and a NUL, nothing when ml is 0 +fn snp msg edit uchar 256 ml ulong t view uchar 128 n ulong to void +if eq ml 0 +ret +end +m = n +if gt m sub ml 1 +m = sub ml 1 +end +for i ulong m +put msg i get t i +end +put msg m 0 +end + +note "Empty or null code buffer" +fn msgnull t edit uchar 128 to ulong +n = app t 0 8245845148755324229 8 +n = app t n 8026294610952547872 8 +n = app t n 7306640099798705508 8 +ret app t n 114 1 +end + +note "Code buffer length %zu is not a multiple of 4 bytes" +fn msglen t edit uchar 128 v ulong to ulong +n = app t 0 7382915055423352643 8 +n = app t n 7453005948419990886 8 +n = app t n 2123892 3 +n = appdec t n v +n = app t n 2338616625293650208 8 +n = app t n 8100133413977923681 8 +n = app t n 2320515332325795180 8 +ret app t n 495623371106 5 +end + +note "Undefined/unrecognized AArch64 opcode 0x%08x at offset 0x%zx" +fn msgop t edit uchar 128 w ulong o ulong to ulong +n = app t 0 7308895133777555029 8 +n = app t n 8026370503058206564 8 +n = app t n 4692861198728261223 8 +n = app t n 8007457545748968001 8 +n = app t n 8660457703282271088 8 +n = apphex t n w 8 +n = app t n 8315446389458100512 8 +n = app t n 516203508837 5 +ret apphex t n o 1 +end + +note "Function does not terminate with RET (terminates with op %d)" +fn msgret t edit uchar 128 op ulong to ulong +n = app t 0 7957695015192261958 8 +n = app t n 8029390865643299872 8 +n = app t n 7956010554822500468 8 +n = app t n 7526756837608485985 8 +n = app t n 7310512214447051296 8 +n = app t n 8315180248822541682 8 +n = app t n 8101729887664568096 8 +n = app t n 32 1 +n = appdec t n op +ret app t n 41 1 +end + +fn ld32 a view uchar 4096 o ulong to ulong +x = ulong get a add o 3 +x = or shl x 8 ulong get a add o 2 +x = or shl x 8 ulong get a add o 1 +ret or shl x 8 ulong get a o +end + +note the instruction loop of the validator over c words: 0 when valid, else the message length in t +fn valscan code view uchar 4096 c ulong t edit uchar 128 d edit ulong 9 to ulong +for i ulong c +o = mul i 4 +w = ld32 code o +if or ne a64decode w d 0 eq get d 0 0 +ret msgop t w o +end +if and eq i sub c 1 ne get d 0 8 +ret msgret t get d 0 +end +end +ret 0 +end + +note aarch64_validate_code_buffer(code, n, msg, ml): 0, or -1 with the C's message in msg. +note ml above 256 (more capacity than msg has) traps 3 before anything is read or written. +fn a64validate code view uchar 4096 n ulong msg edit uchar 256 ml ulong to long +if gt ml 256 +trap 3 +end +t = new uchar 128 0 +d = new ulong 9 0 +if eq n 0 +k = msgnull t +snp msg ml t k +ret -1 +end +if ne rem n 4 0 +k = msglen t n +snp msg ml t k +ret -1 +end +k = valscan code div n 4 t d +if gt k 0 +snp msg ml t k +ret -1 +end +ret 0 +end + +note ==== parity harness: program mode only; everything above this line is the library ==== +note Reads corpus records on stdin (om/aarch64/parity/corpus.py), writes one result line per record: +note E form f1 f2 f3 f4 one emitter call (aarch64_emit_ into a fresh 4096-byte buffer), then +note the decode of the written word and the round-trip mark (see README) +note P maxlen pos n calls a sequence of emitter calls into one buffer (buffer-full path) +note D word aarch64_decode_instruction +note V len ml bytes aarch64_validate_code_buffer +note Numbers are lowercase hex without leading zeros (words: 8 digits), refusal values signed decimal. + +text enm "add_reg sub_reg mul_reg and_reg orr_reg eor_reg mov_reg movz ret b b_cond cbz cbnz movk adr ldr_uoff str_uoff ldrb_uoff strb_uoff ldr_post str_post ldr_x_post str_x_post subs_imm subs_reg " +text fnm "sf rd rn rm |sf rd rn rm |sf rd rn rm |sf rd rn rm |sf rd rn rm |sf rd rn rm |sf rd rm |sf rd imm16 shift |- |imm26 |cond imm19 |sf rt imm19 |sf rt imm19 |sf rd imm16 shift |rd imm21 |sf rt rn uoff |sf rt rn uoff |rt rn uoff |rt rn uoff |rt rn simm9 |rt rn simm9 |rt rn simm9 |rt rn simm9 |sf rd rn imm12 |sf rd rn rm |" +text tref "A64_LEGACY_FIELD_OUT_OF_RANGE aarch64_emit_" + +global ib uchar 1048576 +global ist ulong 2 +global ob uchar 1048576 +global obn ulong 1 +global fv ulong 4 + +fn inb to ulong +p = get ist 0 +if ge p get ist 1 +r = read 0 ib 0 1048576 +if le r 0 +ret 256 +end +put ist 1 ulong r +p = 0 +end +put ist 0 add p 1 +ret ulong get ib p +end + +fn obflush to void +n = get obn 0 +if gt n 0 +r = write 1 ob 0 n +end +put obn 0 0 +end + +fn ob1 c ulong to void +n = get obn 0 +if ge n 1048576 +obflush +n = 0 +end +put ob n uchar c +put obn 0 add n 1 +end + +fn ohx v ulong to void +ob1 32 +k = ulong 1 +while lt k 16 bound 16 +if eq shr v mul k 4 0 +break +end +k = add k 1 +end +for i ulong k +ob1 hexch and shr v mul sub sub k 1 i 4 15 +end +end + +fn ohx8 v ulong to void +ob1 32 +for i ulong 8 +ob1 hexch and shr v mul sub 7 i 4 15 +end +end + +fn ohxb b ulong to void +ob1 hexch shr b 4 +ob1 hexch and b 15 +end + +fn odec v long to void +if lt v 0 +ob1 45 +end +u = ulong 0 +if lt v 0 +u = add not bitcast ulong v 1 +else +u = ulong v +end +t = new uchar 24 0 +k = ulong 0 +while true bound 21 +put t k uchar add 48 rem u 10 +k = add k 1 +u = div u 10 +if eq u 0 +break +end +end +for i ulong k +ob1 ulong get t sub sub k 1 i +end +end + +fn hexval c ulong to ulong +if and ge c 48 le c 57 +ret sub c 48 +end +if and ge c 97 le c 102 +ret sub c 87 +end +ret 16 +end + +fn rdcode to ulong +c = inb +while or eq c 10 eq c 32 bound 999999 +c = inb +end +ret c +end + +fn rdhex to ulong +c = inb +while eq c 32 bound 999999 +c = inb +end +v = ulong 0 +while lt hexval c 16 bound 17 +v = or shl v 4 hexval c +c = inb +end +ret v +end + +fn sgnl v ulong to long +if ge v 9223372036854775808 +ret neg long add not v 1 +end +ret long v +end + +note the word of emitter form f (1..25, the order of aarch64_encoder.h) on the fields in fv +fn enca f ulong to long +a = get fv 0 +b = get fv 1 +c = get fv 2 +d = get fv 3 +if eq f 1 +ret a64addreg a b c d +end +if eq f 2 +ret a64subreg a b c d +end +if eq f 3 +ret a64mulreg a b c d +end +if eq f 4 +ret a64andreg a b c d +end +if eq f 5 +ret a64orrreg a b c d +end +if eq f 6 +ret a64eorreg a b c d +end +if eq f 7 +ret a64movreg a b c +end +if eq f 8 +ret a64movz a b c d +end +if eq f 9 +ret a64ret +end +if eq f 10 +ret a64b sgnl a +end +if eq f 11 +ret a64bcond sgnl a sgnl b +end +if eq f 12 +ret a64cbz a b sgnl c +end +ret encb f +end + +fn encb f ulong to long +a = get fv 0 +b = get fv 1 +c = get fv 2 +d = get fv 3 +if eq f 13 +ret a64cbnz a b sgnl c +end +if eq f 14 +ret a64movk a b c d +end +if eq f 15 +ret a64adr a sgnl b +end +if eq f 16 +ret a64ldruoff a b c d +end +if eq f 17 +ret a64struoff a b c d +end +if eq f 18 +ret a64ldrbuoff a b c +end +if eq f 19 +ret a64strbuoff a b c +end +if eq f 20 +ret a64ldrpost a b sgnl c +end +if eq f 21 +ret a64strpost a b sgnl c +end +if eq f 22 +ret a64ldrxpost a b sgnl c +end +if eq f 23 +ret a64strxpost a b sgnl c +end +if eq f 24 +ret a64subsimm a b c d +end +if eq f 25 +ret a64subsreg a b c d +end +trap 9 +end + +note print the k-th (from 1) space-ended word of the f-th |-ended entry of fnm +fn ofield f ulong k ulong to void +e = ulong 1 +w = ulong 1 +for i ulong len fnm +c = ulong get fnm i +if eq c 124 +e = add e 1 +w = 1 +continue +end +if eq c 32 +w = add w 1 +continue +end +if and eq e f eq w k +ob1 c +end +end +end + +fn oname f ulong to void +e = ulong 1 +for i ulong len enm +c = ulong get enm i +if eq c 32 +e = add e 1 +continue +end +if eq e f +ob1 c +end +end +end + +note the C's stderr line for a refusal code r of form f +fn orefuse f ulong r long to void +for i ulong len tref +ob1 ulong get tref i +end +oname f +ob1 32 +k = ulong sub neg r 1 +ofield f k +ob1 61 +odec sgnl get fv sub k 1 +end + +fn sx v ulong bits ulong to long +h = shl ulong 1 sub bits 1 +if ge v h +ret sub long v long shl h 1 +end +ret long v +end + +note re-encode a decoded word whose op carries every field (-100 for the others) +fn reenc d edit ulong 9 to long +op = get d 0 +if and ge op 1 le op 6 +ret enc4 op get d 1 get d 2 get d 3 get d 4 +end +if eq op 7 +ret a64movz get d 1 get d 2 get d 5 mul get d 6 16 +end +if eq op 13 +ret a64movk get d 1 get d 2 get d 5 mul get d 6 16 +end +if eq op 8 +ret a64ret +end +if eq op 9 +ret a64b sx get d 7 26 +end +if eq op 10 +ret a64bcond long get d 8 sx get d 7 19 +end +if eq op 11 +ret a64cbz get d 1 get d 2 sx get d 7 19 +end +if eq op 12 +ret a64cbnz get d 1 get d 2 sx get d 7 19 +end +ret -100 +end + +fn enc4 op ulong a ulong b ulong c ulong d ulong to long +if eq op 1 +ret a64addreg a b c d +end +if eq op 2 +ret a64subreg a b c d +end +if eq op 3 +ret a64mulreg a b c d +end +if eq op 4 +ret a64andreg a b c d +end +if eq op 5 +ret a64orrreg a b c d +end +ret a64eorreg a b c d +end + +note for a form whose decode drops fields: does the decode show the expected op and the input fields? +fn lossok f ulong d edit ulong 9 to bool +op = get d 0 +if eq f 15 +ret and eq op 14 eq get d 2 get fv 0 +end +if and ge f 20 le f 23 +ret lospost f d +end +if and ge f 18 le f 19 +ok = and eq op sub f 1 eq get d 2 get fv 0 +ret and ok eq get d 3 get fv 1 +end +if or lt f 16 gt f 25 +ret false +end +note forms 16 17 24 25: op, sf, rd, rn; and rm (0 for subs_imm) for 24 25 +eop = sub f 1 +if ge f 24 +eop = 19 +end +ok = and eq op eop eq get d 1 get fv 0 +ok = and ok eq get d 2 get fv 1 +ok = and ok eq get d 3 get fv 2 +if eq f 24 +ok = and ok eq get d 4 0 +end +if eq f 25 +ok = and ok eq get d 4 get fv 3 +end +ret ok +end + +fn lospost f ulong d edit ulong 9 to bool +eop = ulong 15 +if or eq f 21 eq f 23 +eop = 16 +end +esf = ulong 0 +if ge f 22 +esf = 1 +end +ok = and eq get d 0 eop eq get d 1 esf +ok = and ok eq get d 2 get fv 0 +ret and ok eq get d 3 get fv 1 +end + +note E form f1 f2 f3 f4 +fn doenc to void +b = new uchar 4096 170 +st = new ulong 2 0 +d = new ulong 9 0 +f = rdhex +for i ulong 4 +put fv i rdhex +end +put st 1 4096 +w = enca f +if lt w 0 +orefuse f w +ret +end +r = a64put b st w +x = ld32 b 0 +ob1 69 +ohx8 x +ohx bitcast ulong a64decode x d +for i ulong 9 +ohx get d i +end +ob1 32 +e = reenc d +if ge e 0 +if eq ulong e x +ob1 61 +else +ob1 33 +end +ret +end +if lossok f d +ob1 126 +else +ob1 33 +end +end + +note P maxlen pos n, then n times form f1 f2 f3 f4 +fn dobuf to void +b = new uchar 4096 170 +st = new ulong 2 0 +put st 1 rdhex +p0 = rdhex +put st 0 p0 +n = rdhex +ob1 80 +for j ulong n +f = rdhex +for i ulong 4 +put fv i rdhex +end +ob1 32 +odec a64put b st enca f +end +ohx get st 0 +ob1 32 +e = add p0 mul n 4 +if gt e 4096 +e = 4096 +end +for i ulong sub e p0 +ohxb ulong get b add p0 i +end +end + +fn dodec to void +d = new ulong 9 0 +w = rdhex +ob1 68 +ohx bitcast ulong a64decode w d +for i ulong 9 +ohx get d i +end +end + +note V len ml bytes: bytes is one hex token of len bytes ("-" when empty) +fn doval to void +code = new uchar 4096 0 +msg = new uchar 256 170 +n = rdhex +ml = rdhex +c = inb +while eq c 32 bound 999999 +c = inb +end +k = ulong 0 +while lt hexval c 16 bound 999999 +e = inb +put code k uchar or shl hexval c 4 hexval e +k = add k 1 +c = inb +end +r = a64validate code n msg ml +ob1 86 +ob1 32 +odec r +ob1 32 +for i ulong 100 +ohxb ulong get msg i +end +end + +fn main to int +for q ulong 4294967296 +c = rdcode +if eq c 256 +break +end +if eq c 69 +doenc +end +if eq c 80 +dobuf +end +if eq c 68 +dodec +end +if eq c 86 +doval +end +ob1 10 +end +obflush +ret 0 +end diff --git a/om/aarch64/parity/corpus.py b/om/aarch64/parity/corpus.py new file mode 100755 index 000000000..ba6a9d262 --- /dev/null +++ b/om/aarch64/parity/corpus.py @@ -0,0 +1,426 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: Apache-2.0 +"""corpus.py DIR: write the deterministic parity corpus of om/aarch64/aarch64.om into DIR, one file per +stream (STREAM.txt), and print "STREAM RECORDS" per stream on stdout. + +Record formats (all numbers lowercase hex; a signed field is its 64-bit two's complement): + E form f1 f2 f3 f4 one aarch64_emit_ call; form 1..25 in the order of aarch64_encoder.h, + fields in the C parameter order after max_len, unused fields 0 + P maxlen pos n {form f1 f2 f3 f4}*n a sequence of emitter calls into one 4096-byte buffer + D word aarch64_decode_instruction + V len ml bytes aarch64_validate_code_buffer(bytes, len, msg, ml); bytes one hex token, "-" empty + +Every field value is inside its C parameter type (bool, uint8_t, uint16_t, int16_t, int32_t), so the C +receives it unchanged; values outside the architectural ranges inside those types are swept on purpose +(the C refuses them). Generators are splitmix64 with fixed seeds; nothing here reads the C or the .om. +""" +import os +import sys + +M64 = (1 << 64) - 1 + +# form: (C name, field kinds); kinds: b bool, r uint8_t register, u8 uint8_t, u16 uint16_t, +# s16 int16_t, s32 int32_t +FORMS = [ + None, + ("add_reg", "b r r r"), ("sub_reg", "b r r r"), ("mul_reg", "b r r r"), ("and_reg", "b r r r"), + ("orr_reg", "b r r r"), ("eor_reg", "b r r r"), ("mov_reg", "b r r"), ("movz", "b r u16 u8"), + ("ret", ""), ("b", "s32"), ("b_cond", "s32 s32"), ("cbz", "b r s32"), ("cbnz", "b r s32"), + ("movk", "b r u16 u8"), ("adr", "r s32"), ("ldr_uoff", "b r r u16"), ("str_uoff", "b r r u16"), + ("ldrb_uoff", "r r u16"), ("strb_uoff", "r r u16"), ("ldr_post", "r r s16"), ("str_post", "r r s16"), + ("ldr_x_post", "r r s16"), ("str_x_post", "r r s16"), ("subs_imm", "b r r u16"), ("subs_reg", "b r r r"), +] + + +class Rng: + def __init__(self, seed): + self.s = seed & M64 + + def next(self): + self.s = (self.s + 0x9E3779B97F4A7C15) & M64 + z = self.s + z = ((z ^ (z >> 30)) * 0xBF58476D1CE4E5B9) & M64 + z = ((z ^ (z >> 27)) * 0x94D049BB133111EB) & M64 + return z ^ (z >> 31) + + def below(self, n): + return self.next() % n + + def range(self, lo, hi): + """uniform in [lo, hi]""" + return lo + self.below(hi - lo + 1) + + +TYPE = {"b": (0, 1), "r": (0, 255), "u8": (0, 255), "u16": (0, 65535), "s16": (-32768, 32767), + "s32": (-(1 << 31), (1 << 31) - 1)} + + +def h(v): + return "%x" % (v & M64) + + +def rec_e(form, fields): + kinds = FORMS[form][1].split() + assert len(fields) == len(kinds), (form, fields) + for k, v in zip(kinds, fields): + lo, hi = TYPE[k] + assert lo <= v <= hi, (form, fields) + f = list(fields) + [0] * (4 - len(fields)) + return "E %x %s" % (form, " ".join(h(v) for v in f)) + + +# in-range field values per form, for the P stream and the fillers of the sweeps +def valid_fields(rng, form): + name, kinds = FORMS[form] + sf = rng.below(2) + r = lambda: rng.below(32) + if kinds == "b r r r": + return [sf, r(), r(), r()] + if form == 7: + return [sf, r(), r()] + if form in (8, 14): + return [sf, r(), rng.below(65536), 16 * rng.below(4 if sf else 2)] + if form == 9: + return [] + if form == 10: + return [rng.range(-(1 << 25), (1 << 25) - 1)] + if form == 11: + return [rng.below(16), rng.range(-(1 << 18), (1 << 18) - 1)] + if form in (12, 13): + return [sf, r(), rng.range(-(1 << 18), (1 << 18) - 1)] + if form == 15: + return [r(), rng.range(-(1 << 20), (1 << 20) - 1)] + if form in (16, 17): + return [sf, r(), r(), rng.below(4096) * (8 if sf else 4)] + if form in (18, 19): + return [r(), r(), rng.below(4096)] + if form in (20, 21, 22, 23): + return [r(), r(), rng.range(-256, 255)] + if form == 24: + return [sf, r(), r(), rng.below(4096)] + raise AssertionError(form) + + +def full_random(rng, form): + """every field uniform over its whole C type""" + out = [] + for k in FORMS[form][1].split(): + lo, hi = TYPE[k] + out.append(rng.range(lo, hi)) + return out + + +def edge_set(bits): + """signed boundaries of a bits-wide immediate and of int32""" + lo, hi = -(1 << (bits - 1)), (1 << (bits - 1)) - 1 + s = set() + for c in (lo, hi, 0, -1, 1): + for d in range(-3, 4): + s.add(c + d) + s.update([-(1 << 31), (1 << 31) - 1, -(1 << 31) + 1, (1 << 31) - 2, 1 << bits, -(1 << bits)]) + return sorted(v for v in s if -(1 << 31) <= v < (1 << 31)) + + +def gen_rrr(form, rng): + out = [] + for sf in range(2): + for rd in range(32): + for rn in range(32): + for rm in range(32): + out.append([sf, rd, rn, rm]) + for pos in (1, 2, 3): + for v in range(32, 256): + f = valid_fields(rng, form) + f[pos] = v + out.append(f) + for _ in range(200): + out.append(full_random(rng, form)) + return out + + +def gen_movreg(rng): + out = [[sf, rd, rm] for sf in range(2) for rd in range(32) for rm in range(32)] + for pos in (1, 2): + for v in range(32, 256): + f = valid_fields(rng, 7) + f[pos] = v + out.append(f) + for _ in range(200): + out.append(full_random(rng, 7)) + return out + + +def gen_wide(form, rng): + out = [] + for sf in range(2): + for rd in range(256): + for sh in range(256): + out.append([sf, rd, rng.below(65536), sh]) + for imm in range(65536): + out.append([1, rng.below(32), imm, 16 * (imm % 4)]) + for _ in range(10000): + out.append(full_random(rng, form)) + return out + + +def gen_imm_only(form, bits, rng): + """b: every edge, three exhaustive windows, 10,000 in range, 10,000 over int32""" + lo, hi = -(1 << (bits - 1)), (1 << (bits - 1)) - 1 + vals = set(edge_set(bits)) + for c in (lo, 0, hi): + vals.update(range(c - 4096, c + 4097)) + out = [[v] for v in sorted(vals)] + for _ in range(10000): + out.append([rng.range(lo, hi)]) + for _ in range(10000): + out.append(full_random(rng, form)) + return out + + +def gen_bcond(rng): + conds = list(range(-3, 20)) + [255, 256, -(1 << 31), (1 << 31) - 1] + out = [[c, v] for c in conds for v in edge_set(19)] + for c in range(16): + for v in range(-512, 513): + out.append([c, v]) + for _ in range(10000): + out.append(valid_fields(rng, 11)) + for _ in range(10000): + out.append([rng.range(-2, 17), rng.range(-(1 << 31), (1 << 31) - 1)]) + return out + + +def gen_cb(form, rng): + out = [[sf, rt, v] for sf in range(2) for rt in range(256) for v in edge_set(19)] + for _ in range(10000): + out.append(valid_fields(rng, form)) + for _ in range(10000): + out.append(full_random(rng, form)) + return out + + +def gen_adr(rng): + out = [[rd, v] for rd in range(256) for v in edge_set(21)] + for v in range(-4096, 4097): + out.append([rng.below(32), v]) + for _ in range(10000): + out.append(valid_fields(rng, 15)) + for _ in range(10000): + out.append(full_random(rng, 15)) + return out + + +def gen_ls(form, rng): + out = [[sf, rng.below(32), rng.below(32), u] for sf in range(2) for u in range(65536)] + for rt in range(256): + for rn in range(256): + sf = rng.below(2) + out.append([sf, rt, rn, rng.below(4096) * (8 if sf else 4)]) + return out + + +def gen_lsb(form, rng): + out = [[rng.below(32), rng.below(32), u] for u in range(65536)] + for rt in range(256): + for rn in range(256): + u = rng.below(4096) if rng.below(4) else rng.below(65536) + out.append([rt, rn, u]) + return out + + +def gen_post(form, rng): + out = [[rng.below(32), rng.below(32), v] for v in range(-32768, 32768)] + for rt in range(256): + for rn in range(256): + v = rng.range(-256, 255) if rng.below(4) else rng.range(-32768, 32767) + out.append([rt, rn, v]) + return out + + +def gen_subsimm(rng): + out = [[sf, rng.below(32), rng.below(32), u] for sf in range(2) for u in range(65536)] + for rd in range(256): + for rn in range(256): + out.append([rng.below(2), rd, rn, rng.below(4096)]) + return out + + +def enc_stream(form): + rng = Rng(0xA64E0000 + form) + if FORMS[form][1] == "b r r r": + rows = gen_rrr(form, rng) + elif form == 7: + rows = gen_movreg(rng) + elif form in (8, 14): + rows = gen_wide(form, rng) + elif form == 9: + rows = [[]] + elif form == 10: + rows = gen_imm_only(form, 26, rng) + elif form == 11: + rows = gen_bcond(rng) + elif form in (12, 13): + rows = gen_cb(form, rng) + elif form == 15: + rows = gen_adr(rng) + elif form in (16, 17): + rows = gen_ls(form, rng) + elif form in (18, 19): + rows = gen_lsb(form, rng) + elif form in (20, 21, 22, 23): + rows = gen_post(form, rng) + else: + rows = gen_subsimm(rng) + if form != 9: + # 10,000 more calls with every field in range (words for the decode and round-trip checks) + rows += [valid_fields(rng, form) for _ in range(10000)] + return [rec_e(form, r) for r in rows] + + +def buf_stream(): + rng = Rng(0xA64B0F) + out = [] + + def calls(n): + parts = [] + for _ in range(n): + form = rng.range(1, 25) + f = valid_fields(rng, form) + parts.append(rec_e(form, f)[2:]) + return parts + + for maxlen in range(0, 41): + for pos in range(0, maxlen + 9): + n = rng.range(1, 12) + out.append("P %x %x %x %s" % (maxlen, pos, n, " ".join(calls(n)))) + for maxlen, pos, n in ((4096, 4092, 1), (4096, 4088, 2), (4096, 4093, 1), (4096, 4096, 1), (4095, 4092, 1), + (4096, 0, 1024), (4096, 2048, 512), (M64, 0, 64), (M64, 4092, 1), (1 << 63, 4000, 24), + (4097, 4092, 1), (5000, 4090, 1)): + out.append("P %x %x %x %s" % (maxlen, pos, n, " ".join(calls(n)))) + for _ in range(2000): + n = rng.range(1, 40) + pos = rng.range(0, 4096 - 4 * n) + maxlen = rng.range(0, 4096) + out.append("P %x %x %x %s" % (maxlen, pos, n, " ".join(calls(n)))) + return out + + +# the decoder's checks, only to place corpus words in or near its classes (not an oracle) +PATTERNS = [(0xFC000000, 0x14000000), (0xFF000010, 0x54000000), (0x7F000000, 0x34000000), + (0x7F000000, 0x35000000), (0x7F800000, 0x52800000), (0x7FE07C00, 0x1B007C00), + (0x7F200000, 0x0A000000), (0x7F200000, 0x2A000000), (0x7F200000, 0x4A000000), + (0x7F200000, 0x0B000000), (0x7F200000, 0x4B000000), (0x7F800000, 0x72800000), + (0x9F000000, 0x10000000), (0xBF400000, 0xB9400000), (0xBF400000, 0xB9000000), + (0xBFE00400, 0xB8400400), (0xBFE00400, 0xB8000400), (0xFFC00000, 0x39400000), + (0xFFC00000, 0x39000000), (0x7F800000, 0x71000000), (0x7F200000, 0x6B000000)] +RET = 0xD65F03C0 + + +def classed(w): + return w == RET or any((w & m) == p for m, p in PATTERNS) + + +def dec_stream(): + rng = Rng(0xA64D0C) + words = [] + for _ in range(200000): + words.append(rng.next() & 0xFFFFFFFF) + # every value of the bits the decoder tests (mask 0xFFE07C10, 17 bits), twice, other bits random + disc = [b for b in range(32) if (0xFFE07C10 >> b) & 1] + assert len(disc) == 17 + for v in range(1 << 17): + base = 0 + for i, b in enumerate(disc): + if (v >> i) & 1: + base |= 1 << b + for _ in range(2): + words.append(base | (rng.next() & ~0xFFE07C10 & 0xFFFFFFFF)) + words.append(RET) + for b in range(32): + words.append(RET ^ (1 << b)) + for m, p in PATTERNS: + words.append(p) + words.append(p | (~m & 0xFFFFFFFF)) + for b in range(32): + words.append(p ^ (1 << b)) + words += [0, 0xFFFFFFFF] + return ["D %x" % w for w in words] + + +def val_stream(): + rng = Rng(0xA64FA1) + out = [] + + def good(): + while True: + m, p = PATTERNS[rng.below(len(PATTERNS))] + w = p | (rng.next() & ~m & 0xFFFFFFFF) + if classed(w): + return w + + def bad(): + while True: + w = rng.next() & 0xFFFFFFFF + if not classed(w): + return w + + def code(ws): + return "".join("%02x" % ((w >> (8 * i)) & 255) for w in ws for i in range(4)) or "-" + + def rec(n, ml, ws): + out.append("V %x %x %s" % (n, ml, code(ws))) + + # ml is at most 256, the msg array of a64validate (above it the port traps 3; with ml = SIZE_MAX the + # glibc snprintf of the C drops the last byte, an address-dependent wrap, so it is no contract) + mls = list(range(0, 101)) + [128, 255, 256] + for ml in mls: + rec(0, ml, []) + rec(6, ml, [RET, RET]) + rec(0xFFFFFFFFFFFFFFFF, ml, []) + rec(8, ml, [RET, 0]) + rec(8, ml, [0xF2FFFFE1 | 0, RET]) + rec(8, ml, [good(), 0x8B030041]) + for n in (1, 2, 3, 5, 7, 4095, 4097, 1 << 63, (1 << 63) + 2, M64 - 2, 12345678901234567): + rec(n, 256, []) + # every op as the terminal word (the "terminates with op %d" message), and RET + for m, p in PATTERNS: + rec(4, 256, [p]) + rec(12, 256, [RET, good(), p | (~m & 0xFFFFFFFF)]) + rec(4, 256, [RET]) + # huge lengths stopped by a bad first word (the C reads only that word) + for n in (1 << 62, M64 - 3, 4100): + rec(n, 256, [bad()]) + for _ in range(1500): + k = rng.range(1, 1024 if rng.below(8) == 0 else 64) + ws = [good() for _ in range(k - 1)] + [RET] + kind = rng.below(4) + if kind == 1: + ws[rng.below(k)] = bad() + elif kind == 2: + ws[-1] = good() + elif kind == 3 and k > 1: + ws[rng.below(k - 1)] = RET + n = 4 * k + if rng.below(10) == 0: + n -= rng.range(1, 3) + ml = rng.below(101) if rng.below(3) == 0 else 256 + rec(n, ml, ws) + return out + + +def main(): + if len(sys.argv) != 2: + sys.exit(__doc__) + d = sys.argv[1] + os.makedirs(d, exist_ok=True) + streams = [("e%02d_%s" % (f, FORMS[f][0]), lambda f=f: enc_stream(f)) for f in range(1, 26)] + streams += [("buf", buf_stream), ("dec", dec_stream), ("val", val_stream)] + for name, fn in streams: + rows = fn() + with open(os.path.join(d, name + ".txt"), "w") as fh: + fh.write("\n".join(rows) + "\n") + print(name, len(rows)) + + +if __name__ == "__main__": + main() diff --git a/om/aarch64/parity/expected.txt b/om/aarch64/parity/expected.txt new file mode 100644 index 000000000..cbc7daa3d --- /dev/null +++ b/om/aarch64/parity/expected.txt @@ -0,0 +1,31 @@ +# sha256 of the C oracle's output for each corpus stream (parity/corpus.py): src/aarch64_encoder.c and +# src/aarch64_decoder.c built with the Makefile CFLAGS (gcc 13.3.0, -std=gnu11 -O2, aarch64; .text identical +# to a make build of the same sources). stream records sha256 +e01_add_reg 76408 d34f82afae7f04363f922608021bc85608b73c982ff035565f9460249b59ba97 +e02_sub_reg 76408 fff06e70d6c865015670eb2727523ff1e25793fcc9edd79c5584737720c30e3c +e03_mul_reg 76408 965ff324d088dfc28c703164684071db956b9464141ef1375c3950cc080e90d9 +e04_and_reg 76408 7d34ac9c744d219b49c336abf3decf36c6cbfc408d0f3f96a493ebcc0d31b3fb +e05_orr_reg 76408 0198a060ac0c3c6a0179bc8270f5565e66aea13ab2d2ad96b6d61c728b847044 +e06_eor_reg 76408 83f723f4312fcb71624e08c4df636be0f93c87e28aa09da5c9aa7074892c4b07 +e07_mov_reg 12696 580d85f97aa2d95d41619af760143fc438468c479351e739087aa62009bc7a2f +e08_movz 216608 936060e606bbf44121b8ab84947fbd90827450b7754f4920eaebb2a1e9880ce3 +e09_ret 1 52ec7aa3ade2fd7a988b425ce4b74338587d51f10840494fab9dd39dcc12645f +e10_b 54585 5d9922ca82e8d6bde280880372ca05159d7cdbf4488e5e2a8735bc44922abe3d +e11_b_cond 47183 04e02ee33c23975a5fcfb287f5152cdbe496243ba36a1c543b7ed3e2789b3241 +e12_cbz 44848 72b99c9068a1200fcc1cfe195f363b38c3674e0891fd89275432f3989a39e686 +e13_cbnz 44848 f6b1baeca74286e32c7c436054f1882990ad3d9b9b4bf1ef6a61a515e2f6a995 +e14_movk 216608 95748b573ce561bc3c3261932f58dc26aa3547e8600d0e8884e8fe8b50417836 +e15_adr 45617 a5ae0b97ca642c3b860b2df63db0263b8e8d6e36da949b827337beaedfff7cd1 +e16_ldr_uoff 206608 5df1e1425a5ac84daa6d113a22691457e5292d305d9e6d6193996ceeb12c80ea +e17_str_uoff 206608 2c11ff4ecc6ac49b3c95af94e2febfdebf5595ad236a57b96cb0e4be79091243 +e18_ldrb_uoff 141072 ddf5d88e4d6774cca14534952fa11094e8635226f0e4a1320f10c2ca9917bc1b +e19_strb_uoff 141072 39a52e3e7a25a5c45022870dd8709d959ff08845b4f7e9d3248fe5ce4ef02595 +e20_ldr_post 141072 0d5895a35210033fb45d5d2483b568c2b7bd29b95db16472442e0a8a0d5168aa +e21_str_post 141072 237763c2ccec5dc03003f492fca92d444602a9ade8830b02c61273a8fb439d2c +e22_ldr_x_post 141072 8519f999d58e4c4313c347e973492173f85f989cae3bd22f562b3ef597b40825 +e23_str_x_post 141072 354a722c4b475c2d71fd622fb777a0c4bf0a6487a344f95a25dc26fe5623ff66 +e24_subs_imm 206608 ac2f395e5a48888b923a8e17c814d71b42f2968f92c10a60f5dbfada1422e77d +e25_subs_reg 76408 fa0826544bfc8e4c30388ab42ed65c4cdf62bc28fad136cbc901525339c29397 +buf 3201 c97b4729161159534c559e36fad8d73536d5be00012463ea573ebac6231892fc +dec 462893 7d59dab47925545fbca6e220b717dae84a8667eb496be5668eb8520768edef58 +val 2181 2df636069195c7f64d7ecb4e3baa388408adadd1442cf7a8aa2cb08be488cb4d diff --git a/om/aarch64/parity/gas.py b/om/aarch64/parity/gas.py new file mode 100755 index 000000000..69ac27ca5 --- /dev/null +++ b/om/aarch64/parity/gas.py @@ -0,0 +1,107 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: Apache-2.0 +"""gas.py CORPDIR OUTDIR WORKDIR: cross-check words that aarch64.om wrote against GNU as. + +For each encoder stream eNN_*, up to 200 records whose .om output is a word (evenly spaced over the +stream) are written back as assembly text from their fields, assembled with `as`, and the .text words +must equal the .om words. A 31 register is written as xzr/wzr where the form reads ZR and sp where it +reads SP. Exit 0 and one summary line when every word is identical, 1 otherwise. Needs `as` and +`objcopy` for AArch64 on PATH. +""" +import os +import subprocess +import sys + +CC = "eq ne cs cc mi pl vs vc hi ls ge lt gt le al nv".split() + + +def sgn(v): + return v - (1 << 64) if v >> 63 else v + + +def zr(r, sf): + if r == 31: + return "xzr" if sf else "wzr" + return ("x%d" if sf else "w%d") % r + + +def sp(r, sf=1): + if r == 31: + return "sp" if sf else "wsp" + return ("x%d" if sf else "w%d") % r + + +def rel(n): + return ". + %d" % n if n >= 0 else ". - %d" % -n + + +def text(form, f): + a, b, c, d = f + if 1 <= form <= 6 or form == 25: + op = ["", "add", "sub", "mul", "and", "orr", "eor"][form] if form != 25 else "subs" + return "%s %s, %s, %s" % (op, zr(b, a), zr(c, a), zr(d, a)) + if form == 7: + return "orr %s, %s, %s" % (zr(b, a), zr(31, a), zr(c, a)) + if form in (8, 14): + return "%s %s, #%d, lsl #%d" % ("movz" if form == 8 else "movk", zr(b, a), c, d) + if form == 9: + return "ret" + if form == 10: + return "b %s" % rel(4 * sgn(a)) + if form == 11: + return "b.%s %s" % (CC[a], rel(4 * sgn(b))) + if form in (12, 13): + return "%s %s, %s" % ("cbz" if form == 12 else "cbnz", zr(b, a), rel(4 * sgn(c))) + if form == 15: + return "adr %s, %s" % (zr(a, 1), rel(sgn(b))) + if form in (16, 17): + return "%s %s, [%s, #%d]" % ("ldr" if form == 16 else "str", zr(b, a), sp(c), d) + if form in (18, 19): + return "%s %s, [%s, #%d]" % ("ldrb" if form == 18 else "strb", zr(a, 0), sp(b), c) + if 20 <= form <= 23: + op = "ldr" if form in (20, 22) else "str" + return "%s %s, [%s], #%d" % (op, zr(a, form >= 22), sp(b), sgn(c)) + if form == 24: + return "subs %s, %s, #%d" % (zr(b, a), sp(c, a), d) + raise AssertionError(form) + + +def main(): + if len(sys.argv) != 4: + sys.exit(__doc__) + corp, outd, work = sys.argv[1:] + lines, want = [], [] + forms = set() + for name in sorted(os.listdir(corp)): + if not (name.startswith("e") and name.endswith(".txt")): + continue + s = name[:-4] + recs = open(os.path.join(corp, name)).read().split("\n") + outs = open(os.path.join(outd, s + ".out")).read().split("\n") + ok = [i for i, o in enumerate(outs) if o.startswith("E ")] + step = max(1, len(ok) // 200) + for i in ok[::step][:200]: + w = recs[i].split() + form, f = int(w[1], 16), [int(x, 16) for x in w[2:6]] + lines.append(text(form, f)) + want.append(int(outs[i].split()[1], 16)) + forms.add(form) + src = os.path.join(work, "gas.s") + obj = os.path.join(work, "gas.o") + binf = os.path.join(work, "gas.bin") + open(src, "w").write("\n".join(lines) + "\n") + subprocess.run(["as", src, "-o", obj], check=True, stderr=subprocess.DEVNULL) + subprocess.run(["objcopy", "-O", "binary", "--only-section=.text", obj, binf], check=True) + data = open(binf, "rb").read() + got = [int.from_bytes(data[4 * i:4 * i + 4], "little") for i in range(len(data) // 4)] + bad = [i for i in range(len(want)) if i >= len(got) or got[i] != want[i]] + if len(got) != len(want) or bad: + for i in bad[:20]: + print("gas MISMATCH %s: as %s, om %08x" % (lines[i], "%08x" % got[i] if i < len(got) else "-", want[i])) + print("gas FAIL: %d of %d differ" % (len(bad), len(want))) + sys.exit(1) + print("gas: %d words over %d forms identical to GNU as" % (len(want), len(forms))) + + +if __name__ == "__main__": + main() diff --git a/om/aarch64/parity/run.sh b/om/aarch64/parity/run.sh new file mode 100755 index 000000000..51776125f --- /dev/null +++ b/om/aarch64/parity/run.sh @@ -0,0 +1,124 @@ +#!/bin/sh +# SPDX-License-Identifier: Apache-2.0 +# Parity of om/aarch64/aarch64.om against the C it ports (src/aarch64_encoder.c, src/aarch64_decoder.c), +# by RECORDED C output: corpus.py regenerates the corpus, the .om harness runs every stream, and each +# stream's output must hash to parity/expected.txt, the sha256 of the C oracle's output for the same +# stream (recorded when the port was made; the C oracle driver itself is not in the tree, so this script +# does not run any C). Then 23 small mutants of aarch64.om must each change their stream's hash, and +# six inputs outside the C parameter types or the fixed arrays must trap with the named code. +# With `as` and `objcopy` on PATH, up to 200 words per form (4,801) are also assembled from their fields by GNU as and +# compared. With OMEGA_BRIDGE set, the 28 exported functions are cut into function-mode units +# (unit.py), bound by the pinned omega-bridge generator and compiled as C (bindability). +# OMEGA_OMC seed-born omc, sha256 pinned below (exit 3 NOT_RUN without it) +# OMEGA_BRIDGE optional: an aien-dev/omega-bridge checkout whose src/native.om matches the pin +set -eu +OMC_PIN=62775d2a391cfef7cde64e387655caa9809a267093112910ec76bfa568f3712b +NATIVE_PIN=2c2c53f61d4ab302f1a2092c3c32189335dd53f6cf2b388f47a475f99f2c3940 +P=$(cd "$(dirname "$0")" && pwd) +OM=$P/../aarch64.om +[ -n "${OMEGA_OMC:-}" ] || { echo "AARCH64-PARITY NOT_RUN: set OMEGA_OMC"; exit 3; } +[ "$(sha256sum < "$OMEGA_OMC" | cut -c1-64)" = "$OMC_PIN" ] || { echo "AARCH64-PARITY NOT_RUN: omc is not the pinned compiler"; exit 3; } +command -v python3 > /dev/null || { echo "AARCH64-PARITY NOT_RUN: python3 missing"; exit 3; } +T=$(mktemp -d); trap 'rm -rf "$T"' EXIT +python3 "$P/corpus.py" "$T/corp" > "$T/counts" +"$OMEGA_OMC" < "$OM" > "$T/am"; chmod +x "$T/am" +grep -v '^#' "$P/expected.txt" | while read -r s n want; do + "$T/am" < "$T/corp/$s.txt" > "$T/$s.out" + got=$(sha256sum < "$T/$s.out" | cut -c1-64) + lines=$(wc -l < "$T/$s.out") + inputs=$(grep "^$s " "$T/counts" | cut -d' ' -f2) + if [ "$got" = "$want" ] && [ "$lines" = "$n" ] && [ "$inputs" = "$n" ]; then + echo "PASS $s: $n records, output identical to the recorded C oracle output" + else + echo "FAIL $s: $lines records of $inputs inputs, sha256 $got (want $n, $want)"; echo x >> "$T/failed" + fi +done +[ ! -e "$T/failed" ] || { echo "AARCH64-PARITY FAIL"; exit 1; } +[ "$(grep -vc '^#' "$P/expected.txt")" = "$(wc -l < "$T/counts")" ] || { echo "AARCH64-PARITY FAIL: stream lists differ"; exit 1; } +cat "$T"/e*.out | awk '/^E /{w++; m[$NF]++} /^A64_LEGACY/{r++} + END {printf "encoder: %d words (round trip: %d re-encode identical, %d lossy decode with every carried field equal, %d wrong), %d refusals\n", w, m["="], m["~"], m["!"], r; if (m["!"] > 0) exit 1}' \ + || { echo "AARCH64-PARITY FAIL: round trip"; exit 1; } + +# Mutants: name | stream | exact text in aarch64.om (\n for a newline) | replacement +cat > "$T/mutants" <<'EOF' +add_opcode|e01_add_reg|ret a64rrr 184549376 sf rd rn rm|ret a64rrr 167772160 sf rd rn rm +rd_range|e01_add_reg|nu8 rn\nnu8 rm\nif gt rd 31|nu8 rn\nnu8 rm\nif gt rd 32 +movreg_field|e07_mov_reg|if gt rm 31\nret -4|if gt rm 31\nret -3 +movz_shift48|e08_movz|mx = 48|mx = 32 +hw_position|e14_movk|w = or w shl and div sh 16 3 21|w = or w shl and div sh 16 3 22 +b_range|e10_b|if or lt imm -33554432 ge imm 33554432|if or lt imm -33554432 gt imm 33554432 +bcond_cond15|e11_b_cond|if or lt cond 0 gt cond 15|if or lt cond 0 gt cond 14 +cbx_sf|e12_cbz|w = or base shl sf 31\nw = or w shl and bitcast ulong imm 524287 5|w = or base shl sf 30\nw = or w shl and bitcast ulong imm 524287 5 +adr_immlo|e15_adr|w = or 268435456 shl and x 3 29|w = or 268435456 shl and x 3 28 +scaled_max|e16_ldr_uoff|if or ne rem uo sz 0 gt div uo sz 4095|if or ne rem uo sz 0 gt div uo sz 4096 +ldrb_max|e18_ldrb_uoff|if gt uo 4095\nret -4|if gt uo 4096\nret -4 +post_mask|e20_ldr_post|w = or base shl and bitcast ulong imm 511 12|w = or base shl and bitcast ulong imm 255 12 +subs_base|e24_subs_imm|base = 4043309056|base = 3942645760 +put_full|buf|if gt add p 4 get st 1|if ge add p 4 get st 1 +put_byte0|buf|put b p uchar and x 255|put b p uchar and shr x 8 255 +dec_mul_o0|dec|if eq and insn 2145418240 453016576|if eq and insn 2145451008 453016576 +dec_ret_rn|dec|put out 3 30|put out 3 0 +dec_post_sf|dec|if eq m 3091203072\ndregs out 15 insn 30 2|if eq m 3091203072\ndregs out 15 insn 31 2 +dec_bcond_imm|dec|put out 7 and shr insn 5 524287\nret 0\nend\nm = and insn 2130706432|put out 7 and shr insn 4 524287\nret 0\nend\nm = and insn 2130706432 +val_hex8|val|n = apphex t n w 8|n = apphex t n w 7 +val_trunc|val|m = sub ml 1|m = ml +val_last|val|if and eq i sub c 1 ne get d 0 8|if and eq i sub c 2 ne get d 0 8 +val_digit|val|put t add n sub sub k 1 i uchar add 48 rem q 10|put t add n sub sub k 1 i uchar add 49 rem q 10 +EOF +while IFS='|' read -r name s old new; do + python3 - "$OM" "$T/m.om" "$old" "$new" <<'PY' +import sys +src, dst, old, new = sys.argv[1], sys.argv[2], sys.argv[3].replace("\\n", "\n"), sys.argv[4].replace("\\n", "\n") +s = open(src).read() +assert s.count(old + "\n") == 1, "mutant text not found exactly once: " + old +open(dst, "w").write(s.replace(old + "\n", new + "\n")) +PY + "$OMEGA_OMC" < "$T/m.om" > "$T/m"; chmod +x "$T/m" + rc=0; "$T/m" < "$T/corp/$s.txt" > "$T/m.out" 2> /dev/null || rc=$? + got=$(sha256sum < "$T/m.out" | cut -c1-64) + want=$(grep "^$s " "$P/expected.txt" | cut -d' ' -f3) + if [ "$got" = "$want" ]; then echo "mutant $name NOT killed on $s"; echo x >> "$T/failed"; continue; fi + d=$(paste -d'|' "$T/m.out" "$T/$s.out" | awk -F'|' '$1 != $2' | wc -l) + echo "mutant $name killed on $s ($d records differ, exit $rc)" +done < "$T/mutants" +[ ! -e "$T/failed" ] || { echo "AARCH64-PARITY FAIL"; exit 1; } + +# Named limits: record | expected exit (100 + trap code) +cat > "$T/traps" <<'EOF' +E 1 0 100 0 0|105|register 256 is outside uint8_t +E 1 2 0 0 0|105|sf 2 is outside bool +E a 80000000 0 0 0|105|imm26 2^31 is outside int32_t +D 100000000|105|word 2^32 is outside uint32_t +V 4 101 c0035fd6|103|ml 257 is more than the 256-byte msg array +P 2000 ffd 1 9 0 0 0 0|103|a write past the 4096-byte buffer (pos 4093, max_len 8192) +EOF +while IFS='|' read -r rec want why; do + rc=0; printf '%s\n' "$rec" | "$T/am" > /dev/null 2>&1 || rc=$? + if [ "$rc" = "$want" ]; then echo "limit trapped (exit $rc): $why"; else echo "limit FAIL (exit $rc, want $want): $why"; echo x >> "$T/failed"; fi +done < "$T/traps" +[ ! -e "$T/failed" ] || { echo "AARCH64-PARITY FAIL"; exit 1; } + +if command -v as > /dev/null && command -v objcopy > /dev/null && [ "$(uname -m)" = aarch64 ]; then + mkdir "$T/gas" + python3 "$P/gas.py" "$T/corp" "$T" "$T/gas" || { echo "AARCH64-PARITY FAIL: GNU as cross-check"; exit 1; } +else + echo "gas cross-check NOT_RUN: no AArch64 as/objcopy" +fi + +if [ -z "${OMEGA_BRIDGE:-}" ]; then + echo "AARCH64-PARITY PASS (bindability NOT_RUN: set OMEGA_BRIDGE)"; exit 0 +fi +[ "$(sha256sum < "$OMEGA_BRIDGE/src/native.om" | cut -c1-64)" = "$NATIVE_PIN" ] || { echo "AARCH64-PARITY PASS (bindability NOT_RUN: native.om is not the pinned generator)"; exit 0; } +"$OMEGA_OMC" < "$OMEGA_BRIDGE/src/native.om" > "$T/native"; chmod +x "$T/native" +: > "$T/units" +for u in a64addreg a64subreg a64mulreg a64andreg a64orrreg a64eorreg a64movreg a64movz a64ret a64b a64bcond \ + a64cbz a64cbnz a64movk a64adr a64ldruoff a64struoff a64ldrbuoff a64strbuoff a64ldrpost a64strpost \ + a64ldrxpost a64strxpost a64subsimm a64subsreg a64put a64decode a64validate; do + python3 "$P/unit.py" "$OM" "$u" > "$T/u.om" + "$OMEGA_OMC" < "$T/u.om" > "$T/u.bin" + { cat "$T/u.om"; printf '\0'; printf '%08d' "$(wc -c < "$T/u.bin")"; cat "$T/u.bin"; } >> "$T/units" +done +"$T/native" < "$T/units" > "$T/units.c" +cc -std=gnu11 -O2 -Wall -Wextra -Werror -c "$T/units.c" -o "$T/units.o" +echo "bindability: 28 function-mode units accepted by native.om and compiled ($(grep -c ') uint32_t omega_[a-z0-9]*(uint64_t \*result' "$T/units.c") exported functions)" +echo "AARCH64-PARITY PASS" diff --git a/om/aarch64/parity/unit.py b/om/aarch64/parity/unit.py new file mode 100755 index 000000000..29675b4a2 --- /dev/null +++ b/om/aarch64/parity/unit.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: Apache-2.0 +"""unit.py AARCH64.om NAME: print the function-mode unit that exports NAME. + +The unit is NAME and every library function it reaches through calls (the part of aarch64.om +before the parity-harness marker), in file order, with NAME moved to the end: the seeded compiler +enters a function-mode unit at its last function and the omega-bridge native call ABI v1 binds that +one; the others stay private helpers. Note lines before a kept function travel with it. +""" +import sys + +MARK = "note ==== parity harness" + + +def functions(lib): + """[(name, first line incl. leading notes, end line)] of the library.""" + out = [] + i = 0 + while i < len(lib): + w = lib[i].split() + if w[:1] == ["fn"]: + j = i + while j > 0 and lib[j - 1].startswith("note") and not lib[j - 1].startswith("note ----"): + j -= 1 + depth = 0 + for k in range(i, len(lib)): + t = lib[k].split()[:1] + if t and t[0] in ("fn", "if", "while", "for"): + depth += 1 + elif t == ["end"]: + depth -= 1 + if depth == 0: + break + else: + sys.exit("unit.py: %s has no closing end" % w[1]) + out.append((w[1], j, k)) + i = k + 1 + else: + i += 1 + return out + + +def main(): + if len(sys.argv) != 3: + sys.exit(__doc__) + src, name = sys.argv[1], sys.argv[2] + lines = open(src).read().split("\n") + lib = lines[:next(i for i, l in enumerate(lines) if l.startswith(MARK))] + fns = functions(lib) + span = {n: (a, b) for n, a, b in fns} + if name not in span: + sys.exit("unit.py: no function %s" % name) + calls = {} + for n, a, b in fns: + words = set() + for l in lib[a:b + 1]: + if not l.startswith("note"): + words.update(l.split()) + calls[n] = {m for m in words if m in span and m != n} + keep = {name} + todo = [name] + while todo: + for m in calls[todo.pop()]: + if m not in keep: + keep.add(m) + todo.append(m) + order = [n for n, _, _ in fns if n in keep and n != name] + [name] + parts = [] + for n in order: + a, b = span[n] + parts.append("\n".join(lib[a:b + 1])) + sys.stdout.write("note SPDX-License-Identifier: Apache-2.0\nnote generated from om/aarch64/aarch64.om by parity/unit.py %s\n\n" % name) + sys.stdout.write("\n\n".join(parts) + "\n") + + +if __name__ == "__main__": + main()