@gmitch215/folio 1.0.0 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +455 -26
- package/dist/affine-state.d.ts +171 -0
- package/dist/affine-state.js +763 -0
- package/dist/affine.d.ts +160 -0
- package/dist/affine.js +571 -0
- package/dist/bake.d.ts +8 -3
- package/dist/bake.js +5 -2
- package/dist/boundaries.d.ts +59 -0
- package/dist/boundaries.js +127 -0
- package/dist/certified.d.ts +66 -0
- package/dist/certified.js +192 -0
- package/dist/certify.d.ts +98 -0
- package/dist/certify.js +2628 -0
- package/dist/compiler.d.ts +37 -1
- package/dist/compiler.js +116 -1
- package/dist/context.d.ts +47 -0
- package/dist/context.js +139 -0
- package/dist/coordinator.d.ts +1 -1
- package/dist/coordinator.js +54 -5
- package/dist/extract.d.ts +114 -1
- package/dist/extract.js +1011 -242
- package/dist/fold.d.ts +32 -0
- package/dist/fold.js +105 -0
- package/dist/frames.d.ts +20 -2
- package/dist/frames.js +205 -10
- package/dist/inline.d.ts +182 -0
- package/dist/inline.js +766 -0
- package/dist/iteration-admission.d.ts +185 -0
- package/dist/iteration-admission.js +201 -0
- package/dist/iteration-layout.d.ts +135 -0
- package/dist/iteration-layout.js +169 -0
- package/dist/iteration-owner.d.ts +45 -0
- package/dist/iteration-owner.js +223 -0
- package/dist/iteration-worker.d.ts +1 -0
- package/dist/iteration-worker.js +216 -0
- package/dist/iteration.d.ts +329 -0
- package/dist/iteration.js +1210 -0
- package/dist/lease.d.ts +45 -0
- package/dist/lease.js +274 -0
- package/dist/managed.d.ts +78 -0
- package/dist/managed.js +448 -27
- package/dist/memo.d.ts +99 -0
- package/dist/memo.js +250 -0
- package/dist/node.d.ts +61 -5
- package/dist/node.js +421 -23
- package/dist/ownership-redirect.d.ts +30 -0
- package/dist/ownership-redirect.js +179 -0
- package/dist/ownership-slices.d.ts +44 -0
- package/dist/ownership-slices.js +72 -0
- package/dist/ownership.d.ts +161 -0
- package/dist/ownership.js +6568 -0
- package/dist/ranges.d.ts +78 -0
- package/dist/ranges.js +263 -0
- package/dist/read-scan.d.ts +18 -0
- package/dist/read-scan.js +94 -0
- package/dist/read-windows.d.ts +103 -0
- package/dist/read-windows.js +244 -0
- package/dist/router-worker.d.ts +1 -0
- package/dist/router-worker.js +4 -0
- package/dist/router.d.ts +203 -0
- package/dist/router.js +667 -0
- package/dist/runs.d.ts +44 -0
- package/dist/runs.js +182 -0
- package/dist/slices-worker.d.ts +1 -0
- package/dist/slices-worker.js +38 -0
- package/dist/slices.d.ts +126 -0
- package/dist/slices.js +441 -0
- package/dist/tasks.d.ts +14 -4
- package/dist/tasks.js +23 -9
- package/dist/transaction.d.ts +10 -0
- package/package.json +44 -4
package/dist/certify.js
ADDED
|
@@ -0,0 +1,2628 @@
|
|
|
1
|
+
import binaryen from 'binaryen';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
export const CHECKER = 'folio-stream-certifier-2';
|
|
4
|
+
// #region values
|
|
5
|
+
class Refusal extends Error {
|
|
6
|
+
}
|
|
7
|
+
const refuse = (why) => {
|
|
8
|
+
throw new Refusal(why);
|
|
9
|
+
};
|
|
10
|
+
class Undecided extends Error {
|
|
11
|
+
}
|
|
12
|
+
class Jump {
|
|
13
|
+
label;
|
|
14
|
+
value;
|
|
15
|
+
constructor(label, value) {
|
|
16
|
+
this.label = label;
|
|
17
|
+
this.value = value;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
const RETURN = '*return';
|
|
21
|
+
const M32 = (1n << 32n) - 1n;
|
|
22
|
+
const M64 = (1n << 64n) - 1n;
|
|
23
|
+
const mask = (w) => (w === 32 ? M32 : M64);
|
|
24
|
+
const s32 = (x) => BigInt.asIntN(32, x);
|
|
25
|
+
const u32 = (x) => BigInt.asUintN(32, x);
|
|
26
|
+
const norm = (c, s) => {
|
|
27
|
+
const out = new Map();
|
|
28
|
+
for (const [k, v] of s) {
|
|
29
|
+
const n = s32(v);
|
|
30
|
+
if (n)
|
|
31
|
+
out.set(k, n);
|
|
32
|
+
}
|
|
33
|
+
return { t: 'c', c: s32(c), s: out };
|
|
34
|
+
};
|
|
35
|
+
const num = (v) => norm(BigInt(v), new Map());
|
|
36
|
+
const sym = (name) => norm(0n, new Map([[name, 1n]]));
|
|
37
|
+
const isNum = (a) => a.s.size === 0;
|
|
38
|
+
const combine = (a, b, sign) => {
|
|
39
|
+
const s = new Map(a.s);
|
|
40
|
+
for (const [k, v] of b.s)
|
|
41
|
+
s.set(k, (s.get(k) ?? 0n) + sign * v);
|
|
42
|
+
return norm(a.c + sign * b.c, s);
|
|
43
|
+
};
|
|
44
|
+
const cadd = (a, b) => combine(a, b, 1n);
|
|
45
|
+
const csub = (a, b) => combine(a, b, -1n);
|
|
46
|
+
const scale = (a, k) => norm(a.c * k, new Map([...a.s].map(([n, v]) => [n, v * k])));
|
|
47
|
+
const ceq = (a, b) => isNum(csub(a, b)) && csub(a, b).c === 0n;
|
|
48
|
+
const floorDiv = (a, b) => {
|
|
49
|
+
const q = a / b;
|
|
50
|
+
return a % b !== 0n && a < 0n !== b < 0n ? q - 1n : q;
|
|
51
|
+
};
|
|
52
|
+
const ceilDiv = (a, b) => -floorDiv(-a, b);
|
|
53
|
+
/** The integer interval of the form over the symbol ranges. Unknown symbols span the whole word. */
|
|
54
|
+
function span(a, ranges) {
|
|
55
|
+
if (isNum(a)) {
|
|
56
|
+
const v = u32(a.c);
|
|
57
|
+
return [v, v];
|
|
58
|
+
}
|
|
59
|
+
let lo = a.c;
|
|
60
|
+
let hi = a.c;
|
|
61
|
+
for (const [k, co] of a.s) {
|
|
62
|
+
const [l, h] = ranges.get(k) ?? [0n, M32];
|
|
63
|
+
lo += co > 0n ? co * l : co * h;
|
|
64
|
+
hi += co > 0n ? co * h : co * l;
|
|
65
|
+
}
|
|
66
|
+
return [lo, hi];
|
|
67
|
+
}
|
|
68
|
+
const nowrap = (a, ranges) => {
|
|
69
|
+
const [lo, hi] = span(a, ranges);
|
|
70
|
+
return lo >= 0n && hi <= M32;
|
|
71
|
+
};
|
|
72
|
+
function decide(rel, a, b, ranges) {
|
|
73
|
+
const yes = num(1);
|
|
74
|
+
const no = num(0);
|
|
75
|
+
const diff = csub(a, b);
|
|
76
|
+
if (isNum(a) && isNum(b)) {
|
|
77
|
+
const x = u32(a.c);
|
|
78
|
+
const y = u32(b.c);
|
|
79
|
+
const r = { eq: x === y, ne: x !== y, ltu: x < y, leu: x <= y, gtu: x > y, geu: x >= y }[rel];
|
|
80
|
+
return r ? yes : no;
|
|
81
|
+
}
|
|
82
|
+
if (rel === 'eq' || rel === 'ne') {
|
|
83
|
+
let equal;
|
|
84
|
+
if (isNum(diff))
|
|
85
|
+
equal = diff.c === 0n;
|
|
86
|
+
else {
|
|
87
|
+
const [lo, hi] = span(diff, ranges);
|
|
88
|
+
if (lo > -(1n << 32n) && hi < 1n << 32n && (lo > 0n || hi < 0n))
|
|
89
|
+
equal = false;
|
|
90
|
+
}
|
|
91
|
+
if (equal !== undefined)
|
|
92
|
+
return (rel === 'eq') === equal ? yes : no;
|
|
93
|
+
}
|
|
94
|
+
else if (nowrap(a, ranges) && nowrap(b, ranges)) {
|
|
95
|
+
const [al, ah] = span(a, ranges);
|
|
96
|
+
const [bl, bh] = span(b, ranges);
|
|
97
|
+
const always = { ltu: ah < bl, leu: ah <= bl, gtu: al > bh, geu: al >= bh }[rel];
|
|
98
|
+
const never = { ltu: al >= bh, leu: al > bh, gtu: ah <= bl, geu: ah < bl }[rel];
|
|
99
|
+
if (always)
|
|
100
|
+
return yes;
|
|
101
|
+
if (never)
|
|
102
|
+
return no;
|
|
103
|
+
}
|
|
104
|
+
return { t: 'p', rel, a, b };
|
|
105
|
+
}
|
|
106
|
+
const negate = (rel) => ({ eq: 'ne', ne: 'eq', ltu: 'geu', geu: 'ltu', leu: 'gtu', gtu: 'leu' })[rel];
|
|
107
|
+
// #endregion
|
|
108
|
+
// #region concrete arithmetic
|
|
109
|
+
const BINARY = new Map();
|
|
110
|
+
const UNARY = new Map();
|
|
111
|
+
const named = binaryen;
|
|
112
|
+
for (const bits of [32, 64]) {
|
|
113
|
+
for (const op of [
|
|
114
|
+
'Add',
|
|
115
|
+
'Sub',
|
|
116
|
+
'Mul',
|
|
117
|
+
'DivS',
|
|
118
|
+
'DivU',
|
|
119
|
+
'RemS',
|
|
120
|
+
'RemU',
|
|
121
|
+
'And',
|
|
122
|
+
'Or',
|
|
123
|
+
'Xor',
|
|
124
|
+
'Shl',
|
|
125
|
+
'ShrU',
|
|
126
|
+
'ShrS',
|
|
127
|
+
'RotL',
|
|
128
|
+
'RotR',
|
|
129
|
+
'Eq',
|
|
130
|
+
'Ne',
|
|
131
|
+
'LtS',
|
|
132
|
+
'LtU',
|
|
133
|
+
'LeS',
|
|
134
|
+
'LeU',
|
|
135
|
+
'GtS',
|
|
136
|
+
'GtU',
|
|
137
|
+
'GeS',
|
|
138
|
+
'GeU'
|
|
139
|
+
])
|
|
140
|
+
BINARY.set(named[`${op}Int${bits}`], { op, bits });
|
|
141
|
+
for (const op of ['Clz', 'Ctz', 'Popcnt', 'EqZ'])
|
|
142
|
+
UNARY.set(named[`${op}Int${bits}`], { op, bits });
|
|
143
|
+
}
|
|
144
|
+
UNARY.set(named.ExtendS8Int32, { op: 'Extend8S', bits: 32 });
|
|
145
|
+
UNARY.set(named.ExtendS16Int32, { op: 'Extend16S', bits: 32 });
|
|
146
|
+
UNARY.set(named.ExtendS8Int64, { op: 'Extend8S', bits: 64 });
|
|
147
|
+
UNARY.set(named.ExtendS16Int64, { op: 'Extend16S', bits: 64 });
|
|
148
|
+
UNARY.set(named.ExtendS32Int64, { op: 'Extend32S', bits: 64 });
|
|
149
|
+
UNARY.set(named.WrapInt64, { op: 'Wrap', bits: 32 });
|
|
150
|
+
UNARY.set(named.ExtendSInt32, { op: 'ExtendS', bits: 64 });
|
|
151
|
+
UNARY.set(named.ExtendUInt32, { op: 'ExtendU', bits: 64 });
|
|
152
|
+
const COMPARE = new Set(['Eq', 'Ne', 'LtS', 'LtU', 'LeS', 'LeU', 'GtS', 'GtU', 'GeS', 'GeU']);
|
|
153
|
+
function evalBinary(op, bits, a, b) {
|
|
154
|
+
const m = mask(bits);
|
|
155
|
+
const sa = BigInt.asIntN(bits, a);
|
|
156
|
+
const sb = BigInt.asIntN(bits, b);
|
|
157
|
+
const sh = b & BigInt(bits - 1);
|
|
158
|
+
const bool = (x) => (x ? 1n : 0n);
|
|
159
|
+
switch (op) {
|
|
160
|
+
case 'Add':
|
|
161
|
+
return (a + b) & m;
|
|
162
|
+
case 'Sub':
|
|
163
|
+
return (a - b) & m;
|
|
164
|
+
case 'Mul':
|
|
165
|
+
return (a * b) & m;
|
|
166
|
+
case 'And':
|
|
167
|
+
return a & b;
|
|
168
|
+
case 'Or':
|
|
169
|
+
return a | b;
|
|
170
|
+
case 'Xor':
|
|
171
|
+
return a ^ b;
|
|
172
|
+
case 'Shl':
|
|
173
|
+
return (a << sh) & m;
|
|
174
|
+
case 'ShrU':
|
|
175
|
+
return a >> sh;
|
|
176
|
+
case 'ShrS':
|
|
177
|
+
return BigInt.asUintN(bits, sa >> sh);
|
|
178
|
+
case 'RotL':
|
|
179
|
+
return ((a << sh) | (a >> (BigInt(bits) - sh))) & m;
|
|
180
|
+
case 'RotR':
|
|
181
|
+
return ((a >> sh) | (a << (BigInt(bits) - sh))) & m;
|
|
182
|
+
case 'Eq':
|
|
183
|
+
return bool(a === b);
|
|
184
|
+
case 'Ne':
|
|
185
|
+
return bool(a !== b);
|
|
186
|
+
case 'LtU':
|
|
187
|
+
return bool(a < b);
|
|
188
|
+
case 'LeU':
|
|
189
|
+
return bool(a <= b);
|
|
190
|
+
case 'GtU':
|
|
191
|
+
return bool(a > b);
|
|
192
|
+
case 'GeU':
|
|
193
|
+
return bool(a >= b);
|
|
194
|
+
case 'LtS':
|
|
195
|
+
return bool(sa < sb);
|
|
196
|
+
case 'LeS':
|
|
197
|
+
return bool(sa <= sb);
|
|
198
|
+
case 'GtS':
|
|
199
|
+
return bool(sa > sb);
|
|
200
|
+
case 'GeS':
|
|
201
|
+
return bool(sa >= sb);
|
|
202
|
+
case 'DivU':
|
|
203
|
+
case 'RemU':
|
|
204
|
+
if (b === 0n)
|
|
205
|
+
return refuse('constant division by zero');
|
|
206
|
+
return op === 'DivU' ? a / b : a % b;
|
|
207
|
+
default:
|
|
208
|
+
if (op === 'DivS' || op === 'RemS') {
|
|
209
|
+
if (b === 0n || (sa === -(1n << BigInt(bits - 1)) && sb === -1n))
|
|
210
|
+
return refuse('constant signed division traps');
|
|
211
|
+
return BigInt.asUintN(bits, op === 'DivS' ? sa / sb : sa % sb);
|
|
212
|
+
}
|
|
213
|
+
return refuse(`unsupported operation ${op}`);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
function evalUnary(op, bits, a) {
|
|
217
|
+
switch (op) {
|
|
218
|
+
case 'EqZ':
|
|
219
|
+
return a === 0n ? 1n : 0n;
|
|
220
|
+
case 'Clz': {
|
|
221
|
+
let n = 0;
|
|
222
|
+
for (let k = bits - 1; k >= 0 && !((a >> BigInt(k)) & 1n); k--)
|
|
223
|
+
n++;
|
|
224
|
+
return BigInt(n);
|
|
225
|
+
}
|
|
226
|
+
case 'Ctz': {
|
|
227
|
+
let n = 0;
|
|
228
|
+
for (let k = 0; k < bits && !((a >> BigInt(k)) & 1n); k++)
|
|
229
|
+
n++;
|
|
230
|
+
return BigInt(n);
|
|
231
|
+
}
|
|
232
|
+
case 'Popcnt':
|
|
233
|
+
return BigInt(a.toString(2).replaceAll('0', '').length);
|
|
234
|
+
case 'Extend8S':
|
|
235
|
+
return BigInt.asUintN(bits, BigInt.asIntN(8, a));
|
|
236
|
+
case 'Extend16S':
|
|
237
|
+
return BigInt.asUintN(bits, BigInt.asIntN(16, a));
|
|
238
|
+
case 'Extend32S':
|
|
239
|
+
return BigInt.asUintN(bits, BigInt.asIntN(32, a));
|
|
240
|
+
case 'Wrap':
|
|
241
|
+
return a & M32;
|
|
242
|
+
case 'ExtendU':
|
|
243
|
+
return a & M32;
|
|
244
|
+
case 'ExtendS':
|
|
245
|
+
return BigInt.asUintN(64, BigInt.asIntN(32, a));
|
|
246
|
+
default:
|
|
247
|
+
return refuse(`unsupported operation ${op}`);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
// variable layout of a gf2 mask: bit 0 is the constant one, bits 1 to 64 the state, then 8 per input byte
|
|
251
|
+
const LOW = (1n << 65n) - 1n;
|
|
252
|
+
const bitVar = (pos, bit) => 1n << BigInt(65 + 8 * pos + bit);
|
|
253
|
+
const gf = (f) => (f.r === 'gf2' ? f : refuse('mixed rings'));
|
|
254
|
+
const zw = (f) => (f.r === 'z2w' ? f : refuse('mixed rings'));
|
|
255
|
+
const sameWidth = (a, b) => {
|
|
256
|
+
if (a.w !== b.w)
|
|
257
|
+
refuse('operands of different widths');
|
|
258
|
+
};
|
|
259
|
+
// gf2 atom variables live above the byte variables, 64 bits per atom
|
|
260
|
+
const ATOM0 = 8192;
|
|
261
|
+
const BYTES = (1n << BigInt(ATOM0 - 65)) - 1n;
|
|
262
|
+
const STATE = ((1n << 64n) - 1n) << 1n;
|
|
263
|
+
const atomBit = (id, k) => 1n << BigInt(ATOM0 + 64 * id + k);
|
|
264
|
+
let atomIds = new Map();
|
|
265
|
+
let atomList = [];
|
|
266
|
+
// per-atom answers that depend only on the atom, kept so a deep chain of atoms is walked once
|
|
267
|
+
const freeMemo = new Map();
|
|
268
|
+
const opaqueMemo = new Map();
|
|
269
|
+
const positionMemo = new Map();
|
|
270
|
+
const resetAtoms = () => {
|
|
271
|
+
atomIds = new Map();
|
|
272
|
+
atomList = [];
|
|
273
|
+
freeMemo.clear();
|
|
274
|
+
opaqueMemo.clear();
|
|
275
|
+
positionMemo.clear();
|
|
276
|
+
};
|
|
277
|
+
const keyed = (m) => [...m].sort((p, q) => p[0] - q[0]).join(',');
|
|
278
|
+
const formKey = (f) => f.r === 'gf2'
|
|
279
|
+
? `g${f.w}:${f.v.map((m) => m.toString(16)).join('.')}`
|
|
280
|
+
: f.r === 'z2w'
|
|
281
|
+
? `z${f.w}:${f.c}:${f.y}:${keyed(f.b)}:${keyed(f.a)}`
|
|
282
|
+
: `p${f.w}:${f.c}:${f.d.join('.')}:${keyed(f.b)}:${keyed(f.a)}`;
|
|
283
|
+
// wall clock limit of the analysis in progress, set by certifyStream
|
|
284
|
+
let deadline = Infinity;
|
|
285
|
+
function internAtom(op, w, extra, args) {
|
|
286
|
+
if (Date.now() > deadline)
|
|
287
|
+
refuse('analysis time limit');
|
|
288
|
+
const key = `${op}|${w}|${extra}|${args.map(formKey).join('|')}`;
|
|
289
|
+
let id = atomIds.get(key);
|
|
290
|
+
if (id === undefined) {
|
|
291
|
+
if (atomList.length >= 50_000)
|
|
292
|
+
refuse('too many atoms');
|
|
293
|
+
id = atomList.length;
|
|
294
|
+
atomList.push({ op, w, extra, args });
|
|
295
|
+
atomIds.set(key, id);
|
|
296
|
+
}
|
|
297
|
+
return id;
|
|
298
|
+
}
|
|
299
|
+
/** The atom with every argument rewritten, for shifting or renaming byte positions. */
|
|
300
|
+
const rekey = (id, fn) => {
|
|
301
|
+
const atom = atomList[id];
|
|
302
|
+
return internAtom(atom.op, atom.w, atom.extra, atom.args.map(fn));
|
|
303
|
+
};
|
|
304
|
+
const moveAtoms = (m, fn) => {
|
|
305
|
+
let out = 0n;
|
|
306
|
+
let high = m >> BigInt(ATOM0);
|
|
307
|
+
for (let id = 0; high > 0n; id++, high >>= 64n) {
|
|
308
|
+
const block = high & M64;
|
|
309
|
+
if (block)
|
|
310
|
+
out ^= block << BigInt(ATOM0 + 64 * fn(id));
|
|
311
|
+
}
|
|
312
|
+
return out;
|
|
313
|
+
};
|
|
314
|
+
const atomPositions = (ids, positions) => {
|
|
315
|
+
let memo = positionMemo.get(positions);
|
|
316
|
+
if (!memo)
|
|
317
|
+
positionMemo.set(positions, (memo = new Map()));
|
|
318
|
+
const out = new Set();
|
|
319
|
+
for (const id of ids) {
|
|
320
|
+
let found = memo.get(id);
|
|
321
|
+
if (!found) {
|
|
322
|
+
const here = new Set();
|
|
323
|
+
for (const arg of atomList[id].args)
|
|
324
|
+
for (const p of positions(arg))
|
|
325
|
+
here.add(p);
|
|
326
|
+
memo.set(id, (found = [...here]));
|
|
327
|
+
}
|
|
328
|
+
for (const p of found)
|
|
329
|
+
out.add(p);
|
|
330
|
+
}
|
|
331
|
+
return out;
|
|
332
|
+
};
|
|
333
|
+
// operations on bytes alone that are not affine, which become atoms when the state is not involved
|
|
334
|
+
const ATOMIC = new Set([
|
|
335
|
+
'And',
|
|
336
|
+
'Or',
|
|
337
|
+
'Xor',
|
|
338
|
+
'Add',
|
|
339
|
+
'Sub',
|
|
340
|
+
'Mul',
|
|
341
|
+
'Shl',
|
|
342
|
+
'ShrU',
|
|
343
|
+
'ShrS',
|
|
344
|
+
'RotL',
|
|
345
|
+
'RotR',
|
|
346
|
+
'Eq',
|
|
347
|
+
'Ne',
|
|
348
|
+
'LtS',
|
|
349
|
+
'LtU',
|
|
350
|
+
'LeS',
|
|
351
|
+
'LeU',
|
|
352
|
+
'GtS',
|
|
353
|
+
'GtU',
|
|
354
|
+
'GeS',
|
|
355
|
+
'GeU',
|
|
356
|
+
'Clz',
|
|
357
|
+
'Ctz',
|
|
358
|
+
'Popcnt',
|
|
359
|
+
'EqZ'
|
|
360
|
+
]);
|
|
361
|
+
/** The atoms a form mentions. */
|
|
362
|
+
const atomIdsOf = (f) => {
|
|
363
|
+
if (f.r !== 'gf2')
|
|
364
|
+
return [...f.a.keys()];
|
|
365
|
+
const ids = [];
|
|
366
|
+
for (let id = 0, high = f.v.reduce((a, m) => a | m, 0n) >> BigInt(ATOM0); high > 0n; id++, high >>= 64n)
|
|
367
|
+
if (high & M64)
|
|
368
|
+
ids.push(id);
|
|
369
|
+
return ids;
|
|
370
|
+
};
|
|
371
|
+
/** Whether the form depends on the state, directly or through the arguments of an atom. */
|
|
372
|
+
const stateFree = (f) => (f.r === 'gf2'
|
|
373
|
+
? f.v.every((m) => (m & STATE) === 0n)
|
|
374
|
+
: f.r === 'z2w'
|
|
375
|
+
? f.y === 0n
|
|
376
|
+
: !f.d[0] && !f.d[1]) &&
|
|
377
|
+
atomIdsOf(f).every((id) => {
|
|
378
|
+
let free = freeMemo.get(id);
|
|
379
|
+
if (free === undefined)
|
|
380
|
+
freeMemo.set(id, (free = atomList[id].args.every(stateFree)));
|
|
381
|
+
return free;
|
|
382
|
+
});
|
|
383
|
+
/** Whether the form holds an atom of the state that the ring cannot express: a residue is expressed by `zp`. */
|
|
384
|
+
const opaque = (ring, f) => atomIdsOf(f).some((id) => {
|
|
385
|
+
const key = `${ring.name}:${id}`;
|
|
386
|
+
let found = opaqueMemo.get(key);
|
|
387
|
+
if (found === undefined) {
|
|
388
|
+
const at = atomList[id];
|
|
389
|
+
found = at.args.every(stateFree)
|
|
390
|
+
? false
|
|
391
|
+
: ring.name === 'zp' && at.op === 'Res'
|
|
392
|
+
? at.args.some((a) => opaque(ring, a))
|
|
393
|
+
: true;
|
|
394
|
+
opaqueMemo.set(key, found);
|
|
395
|
+
}
|
|
396
|
+
return found;
|
|
397
|
+
});
|
|
398
|
+
const gf2 = {
|
|
399
|
+
name: 'gf2',
|
|
400
|
+
state: (w) => ({ r: 'gf2', w, v: Array.from({ length: w }, (_, k) => 1n << BigInt(k + 1)) }),
|
|
401
|
+
bytes: (pos, width, w) => ({
|
|
402
|
+
r: 'gf2',
|
|
403
|
+
w,
|
|
404
|
+
v: Array.from({ length: w }, (_, k) => (k < 8 * width ? bitVar(pos, k) : 0n))
|
|
405
|
+
}),
|
|
406
|
+
konst: (value, w) => ({
|
|
407
|
+
r: 'gf2',
|
|
408
|
+
w,
|
|
409
|
+
v: Array.from({ length: w }, (_, k) => ((value >> BigInt(k)) & 1n ? 1n : 0n))
|
|
410
|
+
}),
|
|
411
|
+
asConst(f) {
|
|
412
|
+
const g = gf(f);
|
|
413
|
+
let value = 0n;
|
|
414
|
+
for (let k = 0; k < g.w; k++) {
|
|
415
|
+
if (g.v[k] === 1n)
|
|
416
|
+
value |= 1n << BigInt(k);
|
|
417
|
+
else if (g.v[k] !== 0n)
|
|
418
|
+
return undefined;
|
|
419
|
+
}
|
|
420
|
+
return value;
|
|
421
|
+
},
|
|
422
|
+
binary(op, a, b) {
|
|
423
|
+
const x = gf(a);
|
|
424
|
+
const y = gf(b);
|
|
425
|
+
sameWidth(x, y);
|
|
426
|
+
const ca = gf2.asConst(x);
|
|
427
|
+
const cb = gf2.asConst(y);
|
|
428
|
+
const map = (f) => ({
|
|
429
|
+
r: 'gf2',
|
|
430
|
+
w: x.w,
|
|
431
|
+
v: Array.from({ length: x.w }, (_, k) => f(k))
|
|
432
|
+
});
|
|
433
|
+
const bit = (c, k) => (c >> BigInt(k)) & 1n;
|
|
434
|
+
// operands that never both hold a one at a position cannot carry, so add and or are xor
|
|
435
|
+
const disjoint = () => x.v.every((m, k) => m === 0n || y.v[k] === 0n)
|
|
436
|
+
? map((k) => x.v[k] ^ y.v[k])
|
|
437
|
+
: refuse(`${op} may carry`);
|
|
438
|
+
const shiftOf = (c) => {
|
|
439
|
+
if (c === undefined)
|
|
440
|
+
return refuse(`${op} by a data value`);
|
|
441
|
+
return Number(c & BigInt(x.w - 1));
|
|
442
|
+
};
|
|
443
|
+
switch (op) {
|
|
444
|
+
case 'Xor':
|
|
445
|
+
return map((k) => x.v[k] ^ y.v[k]);
|
|
446
|
+
case 'And':
|
|
447
|
+
if (cb !== undefined)
|
|
448
|
+
return map((k) => (bit(cb, k) ? x.v[k] : 0n));
|
|
449
|
+
if (ca !== undefined)
|
|
450
|
+
return map((k) => (bit(ca, k) ? y.v[k] : 0n));
|
|
451
|
+
return refuse('and of two data values');
|
|
452
|
+
case 'Or':
|
|
453
|
+
if (cb !== undefined)
|
|
454
|
+
return map((k) => (bit(cb, k) ? 1n : x.v[k]));
|
|
455
|
+
if (ca !== undefined)
|
|
456
|
+
return map((k) => (bit(ca, k) ? 1n : y.v[k]));
|
|
457
|
+
return disjoint();
|
|
458
|
+
case 'Add':
|
|
459
|
+
return disjoint();
|
|
460
|
+
case 'Sub':
|
|
461
|
+
if (cb === 0n)
|
|
462
|
+
return x;
|
|
463
|
+
if (ca === 0n) {
|
|
464
|
+
// 0 - b * 2^j is one bit b spread over every position from j up
|
|
465
|
+
const at = y.v.findIndex((m) => m !== 0n);
|
|
466
|
+
if (at >= 0 && y.v.every((m, k) => k === at || m === 0n))
|
|
467
|
+
return map((k) => (k >= at ? y.v[at] : 0n));
|
|
468
|
+
// 0 - (all ones or all zeros) is one or zero
|
|
469
|
+
if (y.v.every((m) => m === y.v[0]))
|
|
470
|
+
return map((k) => (k === 0 ? y.v[0] : 0n));
|
|
471
|
+
}
|
|
472
|
+
return refuse('subtraction other than the negation of one bit');
|
|
473
|
+
case 'Mul': {
|
|
474
|
+
const c = cb ?? ca;
|
|
475
|
+
const other = cb !== undefined ? x : y;
|
|
476
|
+
if (c === undefined)
|
|
477
|
+
return refuse('product of two data values');
|
|
478
|
+
if (c === 0n)
|
|
479
|
+
return gf2.konst(0n, x.w);
|
|
480
|
+
if (c === 1n)
|
|
481
|
+
return other;
|
|
482
|
+
if ((c & (c - 1n)) === 0n) {
|
|
483
|
+
const s = c.toString(2).length - 1;
|
|
484
|
+
return gf2.binary('Shl', other, gf2.konst(BigInt(s), x.w));
|
|
485
|
+
}
|
|
486
|
+
return refuse('product by a constant that is not a power of two');
|
|
487
|
+
}
|
|
488
|
+
case 'Shl': {
|
|
489
|
+
const s = shiftOf(cb);
|
|
490
|
+
return map((k) => (k < s ? 0n : x.v[k - s]));
|
|
491
|
+
}
|
|
492
|
+
case 'ShrU': {
|
|
493
|
+
const s = shiftOf(cb);
|
|
494
|
+
return map((k) => x.v[k + s] ?? 0n);
|
|
495
|
+
}
|
|
496
|
+
case 'ShrS': {
|
|
497
|
+
const s = shiftOf(cb);
|
|
498
|
+
return map((k) => x.v[k + s] ?? x.v[x.w - 1]);
|
|
499
|
+
}
|
|
500
|
+
case 'RotL': {
|
|
501
|
+
const s = shiftOf(cb);
|
|
502
|
+
return map((k) => x.v[(k - s + x.w) % x.w]);
|
|
503
|
+
}
|
|
504
|
+
case 'RotR': {
|
|
505
|
+
const s = shiftOf(cb);
|
|
506
|
+
return map((k) => x.v[(k + s) % x.w]);
|
|
507
|
+
}
|
|
508
|
+
default:
|
|
509
|
+
return refuse(`${op} is not affine over gf2`);
|
|
510
|
+
}
|
|
511
|
+
},
|
|
512
|
+
unary(op, a) {
|
|
513
|
+
const x = gf(a);
|
|
514
|
+
const ext = (n) => ({
|
|
515
|
+
r: 'gf2',
|
|
516
|
+
w: x.w,
|
|
517
|
+
v: x.v.map((m, k) => (k < n ? m : x.v[n - 1]))
|
|
518
|
+
});
|
|
519
|
+
switch (op) {
|
|
520
|
+
case 'Wrap':
|
|
521
|
+
return { r: 'gf2', w: 32, v: x.v.slice(0, 32) };
|
|
522
|
+
case 'ExtendU':
|
|
523
|
+
return { r: 'gf2', w: 64, v: [...x.v, ...Array(32).fill(0n)] };
|
|
524
|
+
case 'ExtendS':
|
|
525
|
+
return { r: 'gf2', w: 64, v: [...x.v, ...Array(32).fill(x.v[31])] };
|
|
526
|
+
case 'Extend8S':
|
|
527
|
+
return ext(8);
|
|
528
|
+
case 'Extend16S':
|
|
529
|
+
return ext(16);
|
|
530
|
+
case 'Extend32S':
|
|
531
|
+
return ext(32);
|
|
532
|
+
default:
|
|
533
|
+
return refuse(`${op} of a data value is not affine over gf2`);
|
|
534
|
+
}
|
|
535
|
+
},
|
|
536
|
+
equal(a, b) {
|
|
537
|
+
const x = gf(a);
|
|
538
|
+
const y = gf(b);
|
|
539
|
+
return x.w === y.w && x.v.every((m, k) => m === y.v[k]);
|
|
540
|
+
},
|
|
541
|
+
subst(f, y, shift) {
|
|
542
|
+
const x = gf(f);
|
|
543
|
+
const s = gf(y);
|
|
544
|
+
return {
|
|
545
|
+
r: 'gf2',
|
|
546
|
+
w: x.w,
|
|
547
|
+
v: x.v.map((m) => {
|
|
548
|
+
let acc = 0n;
|
|
549
|
+
const low = m & LOW;
|
|
550
|
+
if (low & 1n)
|
|
551
|
+
acc ^= 1n;
|
|
552
|
+
for (let i = 0; i < 64; i++)
|
|
553
|
+
if ((low >> BigInt(i + 1)) & 1n)
|
|
554
|
+
acc ^= s.v[i] ?? refuse('state width');
|
|
555
|
+
acc ^= (((m >> 65n) & BYTES) << BigInt(8 * shift)) << 65n;
|
|
556
|
+
return acc ^ moveAtoms(m, (id) => rekey(id, (a) => gf2.subst(a, s, shift)));
|
|
557
|
+
})
|
|
558
|
+
};
|
|
559
|
+
},
|
|
560
|
+
remap(f, map) {
|
|
561
|
+
const x = gf(f);
|
|
562
|
+
return {
|
|
563
|
+
r: 'gf2',
|
|
564
|
+
w: x.w,
|
|
565
|
+
v: x.v.map((m) => {
|
|
566
|
+
let acc = m & LOW;
|
|
567
|
+
for (const [from, to] of map)
|
|
568
|
+
acc ^= ((m >> BigInt(65 + 8 * from)) & 255n) << BigInt(65 + 8 * to);
|
|
569
|
+
return acc ^ moveAtoms(m, (id) => rekey(id, (a) => gf2.remap(a, map)));
|
|
570
|
+
})
|
|
571
|
+
};
|
|
572
|
+
},
|
|
573
|
+
parity(a) {
|
|
574
|
+
const x = gf(a);
|
|
575
|
+
return {
|
|
576
|
+
r: 'gf2',
|
|
577
|
+
w: x.w,
|
|
578
|
+
v: x.v.map((_, k) => (k === 0 ? x.v.reduce((p, m) => p ^ m, 0n) : 0n))
|
|
579
|
+
};
|
|
580
|
+
},
|
|
581
|
+
positions(f) {
|
|
582
|
+
const x = gf(f);
|
|
583
|
+
const union = x.v.reduce((a, m) => a | m, 0n);
|
|
584
|
+
const all = (union >> 65n) & BYTES;
|
|
585
|
+
const out = new Set();
|
|
586
|
+
for (let p = 0; all >> BigInt(8 * p) > 0n; p++)
|
|
587
|
+
if ((all >> BigInt(8 * p)) & 255n)
|
|
588
|
+
out.add(p);
|
|
589
|
+
for (const p of atomPositions(atomIdsOf(x), gf2.positions))
|
|
590
|
+
out.add(p);
|
|
591
|
+
return [...out].sort((p, q) => p - q);
|
|
592
|
+
},
|
|
593
|
+
operator(f) {
|
|
594
|
+
const x = gf(f);
|
|
595
|
+
return Array.from({ length: x.w }, (_, i) => {
|
|
596
|
+
let column = 0n;
|
|
597
|
+
for (let k = 0; k < x.w; k++)
|
|
598
|
+
column |= ((x.v[k] >> BigInt(i + 1)) & 1n) << BigInt(k);
|
|
599
|
+
return column;
|
|
600
|
+
});
|
|
601
|
+
},
|
|
602
|
+
zeroStep(f) {
|
|
603
|
+
const x = gf(f);
|
|
604
|
+
if (atomIdsOf(x).length)
|
|
605
|
+
return undefined;
|
|
606
|
+
return x.v.reduce((acc, m, k) => acc | ((m & 1n) << BigInt(k)), 0n);
|
|
607
|
+
},
|
|
608
|
+
lookup(index, offset, width, w, read) {
|
|
609
|
+
const x = gf(index);
|
|
610
|
+
if (x.w !== 32)
|
|
611
|
+
return refuse('table index is not an i32');
|
|
612
|
+
const free = [];
|
|
613
|
+
let origin = 0;
|
|
614
|
+
const linear = x.v.map((m, k) => {
|
|
615
|
+
if (m & 1n)
|
|
616
|
+
origin |= 1 << k;
|
|
617
|
+
const rest = m & ~1n;
|
|
618
|
+
if (rest)
|
|
619
|
+
free.push(k);
|
|
620
|
+
return rest;
|
|
621
|
+
});
|
|
622
|
+
if (free.length > 10)
|
|
623
|
+
return refuse('table index has more than ten free bits');
|
|
624
|
+
const at = (set) => {
|
|
625
|
+
let e = origin;
|
|
626
|
+
free.forEach((k, i) => {
|
|
627
|
+
if ((set >> i) & 1)
|
|
628
|
+
e ^= 1 << k;
|
|
629
|
+
});
|
|
630
|
+
return read((e >>> 0) + offset, width);
|
|
631
|
+
};
|
|
632
|
+
const base = at(0);
|
|
633
|
+
const delta = free.map((_, i) => at(1 << i) ^ base);
|
|
634
|
+
const entries = [];
|
|
635
|
+
let affine = true;
|
|
636
|
+
for (let set = 0; set < 1 << free.length; set++) {
|
|
637
|
+
let expect = base;
|
|
638
|
+
delta.forEach((d, i) => {
|
|
639
|
+
if ((set >> i) & 1)
|
|
640
|
+
expect ^= d;
|
|
641
|
+
});
|
|
642
|
+
const got = at(set);
|
|
643
|
+
entries.push(got);
|
|
644
|
+
if (got !== expect)
|
|
645
|
+
affine = false;
|
|
646
|
+
}
|
|
647
|
+
if (!affine) {
|
|
648
|
+
// a table indexed by the state is not affine and may only reach memory, like any opaque atom
|
|
649
|
+
if (!stateFree(x))
|
|
650
|
+
opaqueWhy ||= 'table is not linear in its index bits';
|
|
651
|
+
const digest = createHash('sha256').update(entries.join(',')).digest('hex');
|
|
652
|
+
const id = internAtom('Table', w, `${origin}:${free.join('.')}:${digest}`, [x]);
|
|
653
|
+
return { r: 'gf2', w, v: Array.from({ length: w }, (_, k) => atomBit(id, k)) };
|
|
654
|
+
}
|
|
655
|
+
return {
|
|
656
|
+
r: 'gf2',
|
|
657
|
+
w,
|
|
658
|
+
v: Array.from({ length: w }, (_, j) => {
|
|
659
|
+
let acc = (base >> BigInt(j)) & 1n ? 1n : 0n;
|
|
660
|
+
free.forEach((k, i) => {
|
|
661
|
+
if ((delta[i] >> BigInt(j)) & 1n)
|
|
662
|
+
acc ^= linear[k];
|
|
663
|
+
});
|
|
664
|
+
return acc;
|
|
665
|
+
})
|
|
666
|
+
};
|
|
667
|
+
}
|
|
668
|
+
};
|
|
669
|
+
const zwNorm = (w, c, y, b, a = new Map()) => {
|
|
670
|
+
const m = mask(w);
|
|
671
|
+
const bytes = new Map();
|
|
672
|
+
for (const [p, v] of b)
|
|
673
|
+
if (v & m)
|
|
674
|
+
bytes.set(p, v & m);
|
|
675
|
+
const atoms = new Map();
|
|
676
|
+
for (const [p, v] of a)
|
|
677
|
+
if (v & m)
|
|
678
|
+
atoms.set(p, v & m);
|
|
679
|
+
return { r: 'z2w', w, c: c & m, y: y & m, b: bytes, a: atoms };
|
|
680
|
+
};
|
|
681
|
+
const sumMaps = (p, q, sign) => {
|
|
682
|
+
const out = new Map(p);
|
|
683
|
+
for (const [k, v] of q)
|
|
684
|
+
out.set(k, (out.get(k) ?? 0n) + sign * v);
|
|
685
|
+
return out;
|
|
686
|
+
};
|
|
687
|
+
const scaleMap = (p, k) => new Map([...p].map(([pos, v]) => [pos, v * k]));
|
|
688
|
+
const rekeyMap = (p, fn) => {
|
|
689
|
+
const out = new Map();
|
|
690
|
+
for (const [id, v] of p) {
|
|
691
|
+
const to = fn(id);
|
|
692
|
+
out.set(to, (out.get(to) ?? 0n) + v);
|
|
693
|
+
}
|
|
694
|
+
return out;
|
|
695
|
+
};
|
|
696
|
+
const z2w = {
|
|
697
|
+
name: 'z2w',
|
|
698
|
+
state: (w) => zwNorm(w, 0n, 1n, new Map()),
|
|
699
|
+
bytes: (pos, width, w) => zwNorm(w, 0n, 0n, new Map(Array.from({ length: width }, (_, j) => [pos + j, 1n << BigInt(8 * j)]))),
|
|
700
|
+
konst: (value, w) => zwNorm(w, value, 0n, new Map()),
|
|
701
|
+
asConst(f) {
|
|
702
|
+
const x = zw(f);
|
|
703
|
+
return x.y === 0n && x.b.size === 0 && x.a.size === 0 ? x.c : undefined;
|
|
704
|
+
},
|
|
705
|
+
binary(op, a, b) {
|
|
706
|
+
const x = zw(a);
|
|
707
|
+
const y = zw(b);
|
|
708
|
+
sameWidth(x, y);
|
|
709
|
+
const ca = z2w.asConst(x);
|
|
710
|
+
const cb = z2w.asConst(y);
|
|
711
|
+
const lin = (p, q, sign) => zwNorm(x.w, p.c + sign * q.c, p.y + sign * q.y, sumMaps(p.b, q.b, sign), sumMaps(p.a, q.a, sign));
|
|
712
|
+
const times = (p, k) => zwNorm(x.w, p.c * k, p.y * k, scaleMap(p.b, k), scaleMap(p.a, k));
|
|
713
|
+
switch (op) {
|
|
714
|
+
case 'Add':
|
|
715
|
+
return lin(x, y, 1n);
|
|
716
|
+
case 'Sub':
|
|
717
|
+
return lin(x, y, -1n);
|
|
718
|
+
case 'Mul':
|
|
719
|
+
if (cb !== undefined)
|
|
720
|
+
return times(x, cb);
|
|
721
|
+
if (ca !== undefined)
|
|
722
|
+
return times(y, ca);
|
|
723
|
+
return refuse('product of two data values');
|
|
724
|
+
case 'Shl':
|
|
725
|
+
if (cb === undefined)
|
|
726
|
+
return refuse('shift by a data value');
|
|
727
|
+
return times(x, 1n << (cb & BigInt(x.w - 1)));
|
|
728
|
+
default:
|
|
729
|
+
return refuse(`${op} is not affine over z2w`);
|
|
730
|
+
}
|
|
731
|
+
},
|
|
732
|
+
unary: (op) => refuse(`${op} of a data value is not affine over z2w`),
|
|
733
|
+
equal(a, b) {
|
|
734
|
+
const x = zw(a);
|
|
735
|
+
const y = zw(b);
|
|
736
|
+
if (x.w !== y.w ||
|
|
737
|
+
x.c !== y.c ||
|
|
738
|
+
x.y !== y.y ||
|
|
739
|
+
x.b.size !== y.b.size ||
|
|
740
|
+
x.a.size !== y.a.size)
|
|
741
|
+
return false;
|
|
742
|
+
for (const [k, v] of x.b)
|
|
743
|
+
if (y.b.get(k) !== v)
|
|
744
|
+
return false;
|
|
745
|
+
for (const [k, v] of x.a)
|
|
746
|
+
if (y.a.get(k) !== v)
|
|
747
|
+
return false;
|
|
748
|
+
return true;
|
|
749
|
+
},
|
|
750
|
+
subst(f, y, shift) {
|
|
751
|
+
const x = zw(f);
|
|
752
|
+
const s = zw(y);
|
|
753
|
+
const bs = scaleMap(s.b, x.y);
|
|
754
|
+
for (const [k, v] of x.b)
|
|
755
|
+
bs.set(k + shift, (bs.get(k + shift) ?? 0n) + v);
|
|
756
|
+
const moved = rekeyMap(x.a, (id) => rekey(id, (a) => z2w.subst(a, s, shift)));
|
|
757
|
+
return zwNorm(x.w, x.c + x.y * s.c, x.y * s.y, bs, sumMaps(scaleMap(s.a, x.y), moved, 1n));
|
|
758
|
+
},
|
|
759
|
+
remap(f, map) {
|
|
760
|
+
const x = zw(f);
|
|
761
|
+
const bs = new Map();
|
|
762
|
+
for (const [k, v] of x.b) {
|
|
763
|
+
const to = map.get(k) ?? k;
|
|
764
|
+
bs.set(to, (bs.get(to) ?? 0n) + v);
|
|
765
|
+
}
|
|
766
|
+
return zwNorm(x.w, x.c, x.y, bs, rekeyMap(x.a, (id) => rekey(id, (a) => z2w.remap(a, map))));
|
|
767
|
+
},
|
|
768
|
+
parity: () => refuse('parity of a data value is not affine over z2w'),
|
|
769
|
+
positions(f) {
|
|
770
|
+
const x = zw(f);
|
|
771
|
+
const out = new Set([...x.b.keys()]);
|
|
772
|
+
for (const p of atomPositions(x.a.keys(), z2w.positions))
|
|
773
|
+
out.add(p);
|
|
774
|
+
return [...out].sort((p, q) => p - q);
|
|
775
|
+
},
|
|
776
|
+
operator: (f) => zw(f).y,
|
|
777
|
+
zeroStep: (f) => (zw(f).a.size ? undefined : zw(f).c),
|
|
778
|
+
lookup: () => refuse('a table lookup is not affine over z2w')
|
|
779
|
+
};
|
|
780
|
+
// #region zp
|
|
781
|
+
const DIGIT = 16;
|
|
782
|
+
const DMAX = (1n << BigInt(DIGIT)) - 1n;
|
|
783
|
+
const zpf = (f) => (f.r === 'zp' ? f : refuse('mixed rings'));
|
|
784
|
+
const zpMake = (w, c, d, b, a) => ({
|
|
785
|
+
r: 'zp',
|
|
786
|
+
w,
|
|
787
|
+
c,
|
|
788
|
+
d,
|
|
789
|
+
b: new Map([...b].filter(([, v]) => v !== 0n)),
|
|
790
|
+
a: new Map([...a].filter(([, v]) => v !== 0n))
|
|
791
|
+
});
|
|
792
|
+
const zpAtom = (w, id) => zpMake(w, 0n, [0n, 0n], new Map(), new Map([[id, 1n]]));
|
|
793
|
+
const zpLin = (p, q, sign) => zpMake(p.w, p.c + sign * q.c, [p.d[0] + sign * q.d[0], p.d[1] + sign * q.d[1]], sumMaps(p.b, q.b, sign), sumMaps(p.a, q.a, sign));
|
|
794
|
+
const zpTimes = (p, k) => zpMake(p.w, p.c * k, [p.d[0] * k, p.d[1] * k], scaleMap(p.b, k), scaleMap(p.a, k));
|
|
795
|
+
const atomRange = (id) => {
|
|
796
|
+
const at = atomList[id];
|
|
797
|
+
if (at.op === 'Res')
|
|
798
|
+
return [0n, BigInt(at.extra) - 1n];
|
|
799
|
+
if (/^(Eq|Ne|EqZ|[LG][te][SU])$/.test(at.op))
|
|
800
|
+
return [0n, 1n];
|
|
801
|
+
if (/^(Clz|Ctz|Popcnt)$/.test(at.op))
|
|
802
|
+
return [0n, BigInt(at.w)];
|
|
803
|
+
return [0n, mask(at.w)];
|
|
804
|
+
};
|
|
805
|
+
/** The integer interval of the form: both digits span 16 bits, a byte 8, an atom its own range. */
|
|
806
|
+
function zpSpan(x) {
|
|
807
|
+
let lo = x.c;
|
|
808
|
+
let hi = x.c;
|
|
809
|
+
const add = (k, l, h) => {
|
|
810
|
+
lo += k > 0n ? k * l : k * h;
|
|
811
|
+
hi += k > 0n ? k * h : k * l;
|
|
812
|
+
};
|
|
813
|
+
for (const k of x.d)
|
|
814
|
+
add(k, 0n, DMAX);
|
|
815
|
+
for (const k of x.b.values())
|
|
816
|
+
add(k, 0n, 255n);
|
|
817
|
+
for (const [id, k] of x.a)
|
|
818
|
+
add(k, ...atomRange(id));
|
|
819
|
+
return [lo, hi];
|
|
820
|
+
}
|
|
821
|
+
const zpFits = (x) => {
|
|
822
|
+
const [lo, hi] = zpSpan(x);
|
|
823
|
+
return lo >= 0n && hi <= mask(x.w);
|
|
824
|
+
};
|
|
825
|
+
const zpChecked = (x, op) => (zpFits(x) ? x : refuse(`${op} may wrap`));
|
|
826
|
+
/**
|
|
827
|
+
* The bits of `x` below and from `s` up as two forms, when every state or byte term is either a
|
|
828
|
+
* multiple of 2^s or sits wholly below it, so the low part provably stays under 2^s.
|
|
829
|
+
*/
|
|
830
|
+
function zpSplit(x, s) {
|
|
831
|
+
if (!zpFits(x))
|
|
832
|
+
return refuse('a split of a value that may wrap');
|
|
833
|
+
const unit = 1n << BigInt(s);
|
|
834
|
+
const low = {
|
|
835
|
+
d: [0n, 0n],
|
|
836
|
+
b: new Map(),
|
|
837
|
+
a: new Map()
|
|
838
|
+
};
|
|
839
|
+
const high = {
|
|
840
|
+
d: [0n, 0n],
|
|
841
|
+
b: new Map(),
|
|
842
|
+
a: new Map()
|
|
843
|
+
};
|
|
844
|
+
const part = (k, to) => k % unit === 0n ? to(high, k / unit) : to(low, k);
|
|
845
|
+
x.d.forEach((k, i) => part(k, (p, v) => (p.d[i] = v)));
|
|
846
|
+
for (const [pos, k] of x.b)
|
|
847
|
+
part(k, (p, v) => p.b.set(pos, v));
|
|
848
|
+
for (const [id, k] of x.a)
|
|
849
|
+
part(k, (p, v) => p.a.set(id, v));
|
|
850
|
+
const cl = ((x.c % unit) + unit) % unit;
|
|
851
|
+
const out = {
|
|
852
|
+
low: zpMake(x.w, cl, low.d, low.b, low.a),
|
|
853
|
+
high: zpMake(x.w, (x.c - cl) / unit, high.d, high.b, high.a)
|
|
854
|
+
};
|
|
855
|
+
const [lo, hi] = zpSpan(out.low);
|
|
856
|
+
if (lo < 0n || hi >= unit)
|
|
857
|
+
return refuse('the low bits of a value may carry into the high bits');
|
|
858
|
+
return out;
|
|
859
|
+
}
|
|
860
|
+
/** `hi + lo` as the or of two forms, when `hi` has zeros below the bits that `lo` can set. */
|
|
861
|
+
function zpDisjoint(hi, lo) {
|
|
862
|
+
let s = hi.w;
|
|
863
|
+
const note = (v) => {
|
|
864
|
+
const m = v < 0n ? -v : v;
|
|
865
|
+
if (m !== 0n)
|
|
866
|
+
s = Math.min(s, (m & -m).toString(2).length - 1);
|
|
867
|
+
};
|
|
868
|
+
note(hi.c);
|
|
869
|
+
hi.d.forEach(note);
|
|
870
|
+
hi.b.forEach(note);
|
|
871
|
+
hi.a.forEach(note);
|
|
872
|
+
if (s === 0)
|
|
873
|
+
return undefined;
|
|
874
|
+
const [l, h] = zpSpan(lo);
|
|
875
|
+
return l >= 0n && h < 1n << BigInt(s) ? zpLin(hi, lo, 1n) : undefined;
|
|
876
|
+
}
|
|
877
|
+
/**
|
|
878
|
+
* `f` mod `p` for a form that holds a value in [0, 2^w). A residue atom stands for its argument
|
|
879
|
+
* mod p, so a residue inside another one folds away and the argument is kept with every coefficient
|
|
880
|
+
* reduced. A value that is already below p is the argument itself.
|
|
881
|
+
*/
|
|
882
|
+
function zpRes(p, f) {
|
|
883
|
+
let c = f.c;
|
|
884
|
+
let d0 = f.d[0];
|
|
885
|
+
let d1 = f.d[1];
|
|
886
|
+
const bytes = new Map(f.b);
|
|
887
|
+
const atoms = new Map();
|
|
888
|
+
for (const [id, k] of f.a) {
|
|
889
|
+
const at = atomList[id];
|
|
890
|
+
if (at.op === 'Res' && at.extra === String(p)) {
|
|
891
|
+
const g = at.args[0];
|
|
892
|
+
c += k * g.c;
|
|
893
|
+
d0 += k * g.d[0];
|
|
894
|
+
d1 += k * g.d[1];
|
|
895
|
+
for (const [pos, v] of g.b)
|
|
896
|
+
bytes.set(pos, (bytes.get(pos) ?? 0n) + k * v);
|
|
897
|
+
for (const [other, v] of g.a)
|
|
898
|
+
atoms.set(other, (atoms.get(other) ?? 0n) + k * v);
|
|
899
|
+
}
|
|
900
|
+
else
|
|
901
|
+
atoms.set(id, (atoms.get(id) ?? 0n) + k);
|
|
902
|
+
}
|
|
903
|
+
const red = (v) => ((v % p) + p) % p;
|
|
904
|
+
const reduce = (m) => new Map([...m].map(([k, v]) => [k, red(v)]));
|
|
905
|
+
const g = zpMake(f.w, red(c), [red(d0), red(d1)], reduce(bytes), reduce(atoms));
|
|
906
|
+
if (!g.d[0] && !g.d[1] && !g.b.size && !g.a.size)
|
|
907
|
+
return g;
|
|
908
|
+
const [lo, hi] = zpSpan(g);
|
|
909
|
+
if (lo >= 0n && hi < p)
|
|
910
|
+
return g;
|
|
911
|
+
return zpAtom(f.w, internAtom('Res', f.w, String(p), [g]));
|
|
912
|
+
}
|
|
913
|
+
/** `x` with both digits replaced by the digits of a state form and its byte positions moved by `shift`. */
|
|
914
|
+
function zpSubst(x, digits, shift) {
|
|
915
|
+
const bytes = new Map();
|
|
916
|
+
for (const [pos, v] of x.b)
|
|
917
|
+
bytes.set(pos + shift, v);
|
|
918
|
+
let out = zpMake(x.w, x.c, [0n, 0n], bytes, new Map());
|
|
919
|
+
if (x.d[0] !== 0n || x.d[1] !== 0n) {
|
|
920
|
+
const [lo, hi] = digits();
|
|
921
|
+
out = zpLin(zpLin(out, zpTimes(lo, x.d[0]), 1n), zpTimes(hi, x.d[1]), 1n);
|
|
922
|
+
}
|
|
923
|
+
for (const [id, k] of x.a) {
|
|
924
|
+
const at = atomList[id];
|
|
925
|
+
const moved = at.op === 'Res'
|
|
926
|
+
? zpRes(BigInt(at.extra), zpSubst(at.args[0], digits, shift))
|
|
927
|
+
: zpAtom(x.w, rekey(id, (a) => zpSubst(zpf(a), digits, shift)));
|
|
928
|
+
out = zpLin(out, zpTimes(moved, k), 1n);
|
|
929
|
+
}
|
|
930
|
+
return out;
|
|
931
|
+
}
|
|
932
|
+
function zpRemap(x, map) {
|
|
933
|
+
const bytes = new Map();
|
|
934
|
+
for (const [pos, v] of x.b) {
|
|
935
|
+
const to = map.get(pos) ?? pos;
|
|
936
|
+
bytes.set(to, (bytes.get(to) ?? 0n) + v);
|
|
937
|
+
}
|
|
938
|
+
let out = zpMake(x.w, x.c, x.d, bytes, new Map());
|
|
939
|
+
for (const [id, k] of x.a) {
|
|
940
|
+
const at = atomList[id];
|
|
941
|
+
const moved = at.op === 'Res'
|
|
942
|
+
? zpRes(BigInt(at.extra), zpRemap(at.args[0], map))
|
|
943
|
+
: zpAtom(x.w, rekey(id, (a) => zpRemap(zpf(a), map)));
|
|
944
|
+
out = zpLin(out, zpTimes(moved, k), 1n);
|
|
945
|
+
}
|
|
946
|
+
return out;
|
|
947
|
+
}
|
|
948
|
+
/** The modulus and the digit matrix of a one byte step whose two digits are each reduced mod one p. */
|
|
949
|
+
function zpFacts(f) {
|
|
950
|
+
const x = zpf(f);
|
|
951
|
+
if (x.w !== 32)
|
|
952
|
+
return refuse('the state is not 32 bits');
|
|
953
|
+
const { low, high } = zpSplit(x, DIGIT);
|
|
954
|
+
let modulus;
|
|
955
|
+
// a digit is one residue atom, or an exact form below the modulus whose atoms ignore the state
|
|
956
|
+
const residue = (digit) => {
|
|
957
|
+
const only = digit.c === 0n &&
|
|
958
|
+
!digit.d[0] &&
|
|
959
|
+
!digit.d[1] &&
|
|
960
|
+
!digit.b.size &&
|
|
961
|
+
digit.a.size === 1 &&
|
|
962
|
+
[...digit.a.values()][0] === 1n;
|
|
963
|
+
const at = only ? atomList[[...digit.a.keys()][0]] : undefined;
|
|
964
|
+
if (at?.op !== 'Res')
|
|
965
|
+
return undefined;
|
|
966
|
+
const q = BigInt(at.extra);
|
|
967
|
+
if (modulus !== undefined && modulus !== q)
|
|
968
|
+
return refuse('the digits reduce by different moduli');
|
|
969
|
+
modulus = q;
|
|
970
|
+
return at.args[0];
|
|
971
|
+
};
|
|
972
|
+
const reduced = [low, high].map(residue);
|
|
973
|
+
if (modulus === undefined)
|
|
974
|
+
return refuse('no digit of the state is reduced');
|
|
975
|
+
const p = modulus;
|
|
976
|
+
if (p > 1n << BigInt(DIGIT))
|
|
977
|
+
return refuse('the modulus does not fit a digit');
|
|
978
|
+
const rows = [low, high].map((digit, i) => {
|
|
979
|
+
const g = reduced[i] ?? digit;
|
|
980
|
+
if (!stateFree(zpMake(g.w, 0n, [0n, 0n], g.b, g.a)))
|
|
981
|
+
return refuse('a digit depends on the state through a second reduction');
|
|
982
|
+
if (!reduced[i]) {
|
|
983
|
+
const [lo, hi] = zpSpan(digit);
|
|
984
|
+
if (lo < 0n || hi >= p)
|
|
985
|
+
return refuse('a digit of the state is not reduced');
|
|
986
|
+
}
|
|
987
|
+
return g.d.map((v) => ((v % p) + p) % p);
|
|
988
|
+
});
|
|
989
|
+
return { modulus: p, matrix: rows.flat() };
|
|
990
|
+
}
|
|
991
|
+
const pow2 = (v) => (v > 0n && (v & (v - 1n)) === 0n ? v.toString(2).length - 1 : -1);
|
|
992
|
+
const zp = {
|
|
993
|
+
name: 'zp',
|
|
994
|
+
state(w) {
|
|
995
|
+
if (w !== 32)
|
|
996
|
+
return refuse('the zp ring holds a 32-bit state');
|
|
997
|
+
return zpMake(w, 0n, [1n, 1n << BigInt(DIGIT)], new Map(), new Map());
|
|
998
|
+
},
|
|
999
|
+
bytes: (pos, width, w) => zpMake(w, 0n, [0n, 0n], new Map(Array.from({ length: width }, (_, j) => [pos + j, 1n << BigInt(8 * j)])), new Map()),
|
|
1000
|
+
konst: (value, w) => zpMake(w, value, [0n, 0n], new Map(), new Map()),
|
|
1001
|
+
asConst(f) {
|
|
1002
|
+
const x = zpf(f);
|
|
1003
|
+
return !x.d[0] && !x.d[1] && !x.b.size && !x.a.size ? x.c : undefined;
|
|
1004
|
+
},
|
|
1005
|
+
binary(op, a, b) {
|
|
1006
|
+
const x = zpf(a);
|
|
1007
|
+
const y = zpf(b);
|
|
1008
|
+
sameWidth(x, y);
|
|
1009
|
+
const ca = zp.asConst(x);
|
|
1010
|
+
const cb = zp.asConst(y);
|
|
1011
|
+
switch (op) {
|
|
1012
|
+
case 'Add':
|
|
1013
|
+
return zpChecked(zpLin(x, y, 1n), op);
|
|
1014
|
+
case 'Sub':
|
|
1015
|
+
return zpChecked(zpLin(x, y, -1n), op);
|
|
1016
|
+
case 'Mul':
|
|
1017
|
+
if (cb !== undefined)
|
|
1018
|
+
return zpChecked(zpTimes(x, cb), op);
|
|
1019
|
+
if (ca !== undefined)
|
|
1020
|
+
return zpChecked(zpTimes(y, ca), op);
|
|
1021
|
+
return refuse('product of two data values');
|
|
1022
|
+
case 'Shl':
|
|
1023
|
+
if (cb === undefined)
|
|
1024
|
+
return refuse('shift by a data value');
|
|
1025
|
+
return zpChecked(zpTimes(x, 1n << (cb & BigInt(x.w - 1))), op);
|
|
1026
|
+
case 'ShrU': {
|
|
1027
|
+
if (cb === undefined)
|
|
1028
|
+
return refuse('shift by a data value');
|
|
1029
|
+
const s = Number(cb & BigInt(x.w - 1));
|
|
1030
|
+
return s === 0 ? x : zpSplit(x, s).high;
|
|
1031
|
+
}
|
|
1032
|
+
case 'And': {
|
|
1033
|
+
const c = cb ?? ca;
|
|
1034
|
+
const other = cb !== undefined ? x : y;
|
|
1035
|
+
if (c === undefined)
|
|
1036
|
+
return refuse('and of two data values');
|
|
1037
|
+
const m = mask(x.w);
|
|
1038
|
+
if (c === m)
|
|
1039
|
+
return other;
|
|
1040
|
+
if (c === 0n)
|
|
1041
|
+
return zp.konst(0n, x.w);
|
|
1042
|
+
const lowBits = pow2(c + 1n);
|
|
1043
|
+
if (lowBits > 0)
|
|
1044
|
+
return zpSplit(other, lowBits).low;
|
|
1045
|
+
const highBits = pow2((~c & m) + 1n);
|
|
1046
|
+
if (highBits > 0)
|
|
1047
|
+
return zpTimes(zpSplit(other, highBits).high, 1n << BigInt(highBits));
|
|
1048
|
+
return refuse('and with a mask that is not a run of low or high bits');
|
|
1049
|
+
}
|
|
1050
|
+
case 'Or':
|
|
1051
|
+
return (zpDisjoint(x, y) ??
|
|
1052
|
+
zpDisjoint(y, x) ??
|
|
1053
|
+
refuse('or of values whose bits may overlap'));
|
|
1054
|
+
case 'RemU': {
|
|
1055
|
+
if (cb === undefined)
|
|
1056
|
+
return refuse('remainder by a data value');
|
|
1057
|
+
if (cb < 2n || cb > 1n << BigInt(DIGIT))
|
|
1058
|
+
return refuse('remainder by a modulus outside 2 to 65536');
|
|
1059
|
+
if (!zpFits(x))
|
|
1060
|
+
return refuse('remainder of a value that may wrap');
|
|
1061
|
+
return zpRes(cb, x);
|
|
1062
|
+
}
|
|
1063
|
+
default:
|
|
1064
|
+
return refuse(`${op} is not affine over zp`);
|
|
1065
|
+
}
|
|
1066
|
+
},
|
|
1067
|
+
unary(op, a) {
|
|
1068
|
+
const x = zpf(a);
|
|
1069
|
+
switch (op) {
|
|
1070
|
+
case 'ExtendU':
|
|
1071
|
+
return x.w === 32 ? { ...x, w: 64 } : refuse('extend of a 64-bit value');
|
|
1072
|
+
case 'Wrap': {
|
|
1073
|
+
const [lo, hi] = zpSpan(x);
|
|
1074
|
+
return lo >= 0n && hi <= M32
|
|
1075
|
+
? { ...x, w: 32 }
|
|
1076
|
+
: refuse('wrap of a value above 32 bits');
|
|
1077
|
+
}
|
|
1078
|
+
default:
|
|
1079
|
+
return refuse(`${op} of a data value is not affine over zp`);
|
|
1080
|
+
}
|
|
1081
|
+
},
|
|
1082
|
+
equal(a, b) {
|
|
1083
|
+
const x = zpf(a);
|
|
1084
|
+
const y = zpf(b);
|
|
1085
|
+
if (x.w !== y.w ||
|
|
1086
|
+
x.c !== y.c ||
|
|
1087
|
+
x.d[0] !== y.d[0] ||
|
|
1088
|
+
x.d[1] !== y.d[1] ||
|
|
1089
|
+
x.b.size !== y.b.size ||
|
|
1090
|
+
x.a.size !== y.a.size)
|
|
1091
|
+
return false;
|
|
1092
|
+
for (const [k, v] of x.b)
|
|
1093
|
+
if (y.b.get(k) !== v)
|
|
1094
|
+
return false;
|
|
1095
|
+
for (const [k, v] of x.a)
|
|
1096
|
+
if (y.a.get(k) !== v)
|
|
1097
|
+
return false;
|
|
1098
|
+
return true;
|
|
1099
|
+
},
|
|
1100
|
+
subst(f, y, shift) {
|
|
1101
|
+
const s = zpf(y);
|
|
1102
|
+
let digits;
|
|
1103
|
+
return zpSubst(zpf(f), () => {
|
|
1104
|
+
if (!digits) {
|
|
1105
|
+
const { low, high } = zpSplit(s, DIGIT);
|
|
1106
|
+
digits = [low, high];
|
|
1107
|
+
}
|
|
1108
|
+
return digits;
|
|
1109
|
+
}, shift);
|
|
1110
|
+
},
|
|
1111
|
+
remap: (f, map) => zpRemap(zpf(f), map),
|
|
1112
|
+
parity: () => refuse('parity of a data value is not affine over zp'),
|
|
1113
|
+
positions(f) {
|
|
1114
|
+
const x = zpf(f);
|
|
1115
|
+
const out = new Set([...x.b.keys()]);
|
|
1116
|
+
for (const p of atomPositions(x.a.keys(), zp.positions))
|
|
1117
|
+
out.add(p);
|
|
1118
|
+
return [...out].sort((p, q) => p - q);
|
|
1119
|
+
},
|
|
1120
|
+
operator: (f) => zpFacts(f).matrix,
|
|
1121
|
+
modulus: (f) => zpFacts(f).modulus,
|
|
1122
|
+
zeroStep(f) {
|
|
1123
|
+
// the value at state zero, when every atom is a residue of a form with no atoms
|
|
1124
|
+
const value = (x) => {
|
|
1125
|
+
let sum = x.c;
|
|
1126
|
+
for (const [id, k] of x.a) {
|
|
1127
|
+
const at = atomList[id];
|
|
1128
|
+
const inner = at.op === 'Res' ? value(at.args[0]) : undefined;
|
|
1129
|
+
if (inner === undefined)
|
|
1130
|
+
return undefined;
|
|
1131
|
+
sum += k * (inner % BigInt(at.extra));
|
|
1132
|
+
}
|
|
1133
|
+
return x.b.size ? undefined : sum;
|
|
1134
|
+
};
|
|
1135
|
+
return value(zpf(f));
|
|
1136
|
+
},
|
|
1137
|
+
lookup: () => refuse('a table lookup is not affine over zp')
|
|
1138
|
+
};
|
|
1139
|
+
// the first operation a ring kept as an atom although the state feeds it, for the reason a refusal gives
|
|
1140
|
+
let opaqueWhy = '';
|
|
1141
|
+
/**
|
|
1142
|
+
* Lets a ring keep an operation it cannot express affinely as an atom. An atom that the state
|
|
1143
|
+
* feeds may be stored to memory, which the output proof allows, but never reaches the state
|
|
1144
|
+
* itself: `Analysis.check` refuses a result that holds one.
|
|
1145
|
+
*/
|
|
1146
|
+
function withAtoms(ring, make) {
|
|
1147
|
+
const binary = ring.binary.bind(ring);
|
|
1148
|
+
const unary = ring.unary.bind(ring);
|
|
1149
|
+
const compare = /^(Eq|Ne|[LG][te][SU])$/;
|
|
1150
|
+
ring.binary = (op, a, b) => {
|
|
1151
|
+
// a value against itself needs no byte to be known
|
|
1152
|
+
if (a.w === b.w && ring.equal(a, b)) {
|
|
1153
|
+
if (op === 'And' || op === 'Or')
|
|
1154
|
+
return a;
|
|
1155
|
+
if (/^(Eq|Le[SU]|Ge[SU])$/.test(op))
|
|
1156
|
+
return ring.konst(1n, 32);
|
|
1157
|
+
if (/^(Ne|Lt[SU]|Gt[SU])$/.test(op))
|
|
1158
|
+
return ring.konst(0n, 32);
|
|
1159
|
+
}
|
|
1160
|
+
try {
|
|
1161
|
+
return binary(op, a, b);
|
|
1162
|
+
}
|
|
1163
|
+
catch (error) {
|
|
1164
|
+
if (!(error instanceof Refusal) || !ATOMIC.has(op))
|
|
1165
|
+
throw error;
|
|
1166
|
+
if (a.w !== b.w)
|
|
1167
|
+
throw error;
|
|
1168
|
+
if (!stateFree(a) || !stateFree(b))
|
|
1169
|
+
opaqueWhy ||= error.message;
|
|
1170
|
+
return make(op, compare.test(op) ? 32 : a.w, '', [a, b], compare.test(op) ? 1 : a.w);
|
|
1171
|
+
}
|
|
1172
|
+
};
|
|
1173
|
+
ring.unary = (op, a) => {
|
|
1174
|
+
try {
|
|
1175
|
+
return unary(op, a);
|
|
1176
|
+
}
|
|
1177
|
+
catch (error) {
|
|
1178
|
+
if (!(error instanceof Refusal) || !ATOMIC.has(op))
|
|
1179
|
+
throw error;
|
|
1180
|
+
if (!stateFree(a))
|
|
1181
|
+
opaqueWhy ||= error.message;
|
|
1182
|
+
return make(op, op === 'EqZ' ? 32 : a.w, '', [a], op === 'EqZ' ? 1 : a.w);
|
|
1183
|
+
}
|
|
1184
|
+
};
|
|
1185
|
+
}
|
|
1186
|
+
withAtoms(gf2, (op, w, extra, args, used) => {
|
|
1187
|
+
const id = internAtom(op, w, extra, args);
|
|
1188
|
+
return {
|
|
1189
|
+
r: 'gf2',
|
|
1190
|
+
w,
|
|
1191
|
+
v: Array.from({ length: w }, (_, k) => (k < used ? atomBit(id, k) : 0n))
|
|
1192
|
+
};
|
|
1193
|
+
});
|
|
1194
|
+
withAtoms(z2w, (op, w, extra, args) => zwNorm(w, 0n, 0n, new Map(), new Map([[internAtom(op, w, extra, args), 1n]])));
|
|
1195
|
+
withAtoms(zp, (op, w, extra, args) => zpAtom(w, internAtom(op, w, extra, args)));
|
|
1196
|
+
// #endregion
|
|
1197
|
+
// #region analysis
|
|
1198
|
+
const MAXPOS = 128n;
|
|
1199
|
+
const PH = 200;
|
|
1200
|
+
const IMAGE = 900;
|
|
1201
|
+
const PAGE = 65536;
|
|
1202
|
+
class Mem {
|
|
1203
|
+
segments;
|
|
1204
|
+
over;
|
|
1205
|
+
reads;
|
|
1206
|
+
limit;
|
|
1207
|
+
constructor(segments, limit, over = new Map(), reads = []) {
|
|
1208
|
+
this.segments = segments;
|
|
1209
|
+
this.limit = limit;
|
|
1210
|
+
this.over = over;
|
|
1211
|
+
this.reads = reads;
|
|
1212
|
+
}
|
|
1213
|
+
clone() {
|
|
1214
|
+
return new Mem(this.segments, this.limit, new Map(this.over), this.reads);
|
|
1215
|
+
}
|
|
1216
|
+
byteAt(address) {
|
|
1217
|
+
const written = this.over.get(address);
|
|
1218
|
+
if (written !== undefined)
|
|
1219
|
+
return written;
|
|
1220
|
+
// segments are applied in order at instantiation, so the last one that covers a byte wins
|
|
1221
|
+
for (let i = this.segments.length - 1; i >= 0; i--) {
|
|
1222
|
+
const seg = this.segments[i];
|
|
1223
|
+
if (address >= seg.start && address < seg.start + seg.bytes.length)
|
|
1224
|
+
return seg.bytes[address - seg.start];
|
|
1225
|
+
}
|
|
1226
|
+
// memory no segment sets is zero when a fresh instance starts; the certificate records the read
|
|
1227
|
+
return address < this.limit ? 0 : undefined;
|
|
1228
|
+
}
|
|
1229
|
+
read(address, width) {
|
|
1230
|
+
let value = 0n;
|
|
1231
|
+
for (let i = 0; i < width; i++) {
|
|
1232
|
+
const b = this.byteAt(address + i);
|
|
1233
|
+
if (b === undefined)
|
|
1234
|
+
return refuse(`read of memory at ${address + i} that no segment sets`);
|
|
1235
|
+
value |= BigInt(b) << BigInt(8 * i);
|
|
1236
|
+
}
|
|
1237
|
+
this.reads.push([address, address + width]);
|
|
1238
|
+
return value;
|
|
1239
|
+
}
|
|
1240
|
+
write(address, width, value) {
|
|
1241
|
+
if (address + width > this.limit)
|
|
1242
|
+
refuse('store outside the initial memory');
|
|
1243
|
+
if (this.over.size >= 65_536)
|
|
1244
|
+
refuse('initialization writes more than 64 KiB');
|
|
1245
|
+
for (let i = 0; i < width; i++)
|
|
1246
|
+
this.over.set(address + i, Number((value >> BigInt(8 * i)) & 255n));
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
/** The offset immediate of a load or store as the unsigned 32-bit value wasm adds to the address. */
|
|
1250
|
+
const imm32 = (v) => BigInt.asUintN(32, BigInt(v.offset));
|
|
1251
|
+
const info = (expr) => {
|
|
1252
|
+
try {
|
|
1253
|
+
return binaryen.getExpressionInfo(expr);
|
|
1254
|
+
}
|
|
1255
|
+
catch {
|
|
1256
|
+
return refuse(`expression kind ${binaryen.getExpressionId(expr)} has no readable form`);
|
|
1257
|
+
}
|
|
1258
|
+
};
|
|
1259
|
+
/** The bits of an i32 or i64 constant, or undefined for another type. */
|
|
1260
|
+
function constBits(v) {
|
|
1261
|
+
if (v.type === binaryen.i32)
|
|
1262
|
+
return BigInt(v.value);
|
|
1263
|
+
if (v.type !== binaryen.i64)
|
|
1264
|
+
return undefined;
|
|
1265
|
+
return typeof v.value === 'bigint'
|
|
1266
|
+
? v.value
|
|
1267
|
+
: (BigInt(v.value.high) << 32n) | BigInt(v.value.low >>> 0);
|
|
1268
|
+
}
|
|
1269
|
+
/** Adds every local that `expr` may set to `out`. Calls run on their own locals and set none of the caller's. */
|
|
1270
|
+
function assigned(expr, out) {
|
|
1271
|
+
const id = binaryen.getExpressionId(expr);
|
|
1272
|
+
if (id === binaryen.NopId || id === binaryen.ConstId || id === binaryen.LocalGetId)
|
|
1273
|
+
return;
|
|
1274
|
+
const v = info(expr);
|
|
1275
|
+
const each = (...kids) => {
|
|
1276
|
+
for (const kid of kids)
|
|
1277
|
+
if (kid)
|
|
1278
|
+
assigned(kid, out);
|
|
1279
|
+
};
|
|
1280
|
+
switch (id) {
|
|
1281
|
+
case binaryen.BlockId:
|
|
1282
|
+
return each(...v.children);
|
|
1283
|
+
case binaryen.LoopId:
|
|
1284
|
+
return each(v.body);
|
|
1285
|
+
case binaryen.BreakId:
|
|
1286
|
+
return each(v.condition, v.value);
|
|
1287
|
+
case binaryen.LocalSetId:
|
|
1288
|
+
out.add(v.index);
|
|
1289
|
+
return each(v.value);
|
|
1290
|
+
case binaryen.UnaryId:
|
|
1291
|
+
case binaryen.DropId:
|
|
1292
|
+
return each(v.value);
|
|
1293
|
+
case binaryen.ReturnId:
|
|
1294
|
+
return each(v.value);
|
|
1295
|
+
case binaryen.BinaryId:
|
|
1296
|
+
return each(v.left, v.right);
|
|
1297
|
+
case binaryen.SelectId:
|
|
1298
|
+
return each(v.ifTrue, v.ifFalse, v.condition);
|
|
1299
|
+
case binaryen.IfId:
|
|
1300
|
+
return each(v.condition, v.ifTrue, v.ifFalse);
|
|
1301
|
+
case binaryen.LoadId:
|
|
1302
|
+
return each(v.ptr);
|
|
1303
|
+
case binaryen.StoreId:
|
|
1304
|
+
return each(v.ptr, v.value);
|
|
1305
|
+
case binaryen.CallId:
|
|
1306
|
+
return each(...v.operands);
|
|
1307
|
+
default:
|
|
1308
|
+
return refuse(`unsupported expression kind ${id}`);
|
|
1309
|
+
}
|
|
1310
|
+
}
|
|
1311
|
+
const substCtl = (a, map) => {
|
|
1312
|
+
let out = num(a.c);
|
|
1313
|
+
for (const [k, co] of a.s)
|
|
1314
|
+
out = cadd(out, scale(map.get(k) ?? sym(k), co));
|
|
1315
|
+
return out;
|
|
1316
|
+
};
|
|
1317
|
+
const divideForm = (a, den, how) => {
|
|
1318
|
+
const s = new Map();
|
|
1319
|
+
for (const [k, v] of a.s) {
|
|
1320
|
+
if (v % den !== 0n)
|
|
1321
|
+
return refuse('loop count is not a whole number of steps');
|
|
1322
|
+
s.set(k, v / den);
|
|
1323
|
+
}
|
|
1324
|
+
if (how === 'exact') {
|
|
1325
|
+
if (a.c % den !== 0n)
|
|
1326
|
+
return refuse('loop count is not a whole number of steps');
|
|
1327
|
+
return norm(a.c / den, s);
|
|
1328
|
+
}
|
|
1329
|
+
return norm(how === 'floor' ? floorDiv(a.c, den) : ceilDiv(a.c, den), s);
|
|
1330
|
+
};
|
|
1331
|
+
class Analysis {
|
|
1332
|
+
ring;
|
|
1333
|
+
callee;
|
|
1334
|
+
depth = 0;
|
|
1335
|
+
body;
|
|
1336
|
+
types;
|
|
1337
|
+
layout;
|
|
1338
|
+
w;
|
|
1339
|
+
block;
|
|
1340
|
+
mem0;
|
|
1341
|
+
allowStore;
|
|
1342
|
+
f1;
|
|
1343
|
+
/** The byte the call stores at offset 0 of one byte, as a form of the state and that byte. */
|
|
1344
|
+
out1;
|
|
1345
|
+
/** True during the one byte call, which has no transform to compare a store with yet. */
|
|
1346
|
+
recording = false;
|
|
1347
|
+
zero;
|
|
1348
|
+
written = new Map();
|
|
1349
|
+
st;
|
|
1350
|
+
ranges = new Map();
|
|
1351
|
+
iterated = new Map();
|
|
1352
|
+
expressions = 0;
|
|
1353
|
+
loops = 0;
|
|
1354
|
+
paths = 0;
|
|
1355
|
+
constructor(ring, fn, layout, block, mem0, allowStore, f1, out1) {
|
|
1356
|
+
this.ring = ring;
|
|
1357
|
+
this.body = fn.body;
|
|
1358
|
+
this.types = fn.types;
|
|
1359
|
+
this.callee = fn.callee;
|
|
1360
|
+
this.layout = layout;
|
|
1361
|
+
this.w = layout.bits;
|
|
1362
|
+
this.block = block;
|
|
1363
|
+
this.mem0 = mem0;
|
|
1364
|
+
this.allowStore = allowStore;
|
|
1365
|
+
this.f1 = f1;
|
|
1366
|
+
this.out1 = out1;
|
|
1367
|
+
}
|
|
1368
|
+
// #region evaluation
|
|
1369
|
+
exec(expr) {
|
|
1370
|
+
if (++this.expressions > 6_000_000)
|
|
1371
|
+
refuse('analysis budget exceeded');
|
|
1372
|
+
if ((this.expressions & 4095) === 0 && Date.now() > deadline)
|
|
1373
|
+
refuse('analysis time limit');
|
|
1374
|
+
const id = binaryen.getExpressionId(expr);
|
|
1375
|
+
if (id === binaryen.NopId)
|
|
1376
|
+
return undefined;
|
|
1377
|
+
const v = info(expr);
|
|
1378
|
+
switch (id) {
|
|
1379
|
+
case binaryen.BlockId: {
|
|
1380
|
+
const name = v.name || undefined;
|
|
1381
|
+
try {
|
|
1382
|
+
let last;
|
|
1383
|
+
for (const child of v.children)
|
|
1384
|
+
last = this.exec(child);
|
|
1385
|
+
return last;
|
|
1386
|
+
}
|
|
1387
|
+
catch (error) {
|
|
1388
|
+
if (error instanceof Jump && name !== undefined && error.label === name)
|
|
1389
|
+
return error.value;
|
|
1390
|
+
throw error;
|
|
1391
|
+
}
|
|
1392
|
+
}
|
|
1393
|
+
case binaryen.LoopId:
|
|
1394
|
+
return this.loop(v);
|
|
1395
|
+
case binaryen.BreakId: {
|
|
1396
|
+
const value = v.value ? this.exec(v.value) : undefined;
|
|
1397
|
+
if (!v.condition)
|
|
1398
|
+
throw new Jump(v.name, value);
|
|
1399
|
+
const taken = this.truth(this.exec(v.condition));
|
|
1400
|
+
if (typeof taken !== 'boolean')
|
|
1401
|
+
throw new Undecided();
|
|
1402
|
+
if (taken)
|
|
1403
|
+
throw new Jump(v.name, value);
|
|
1404
|
+
return value;
|
|
1405
|
+
}
|
|
1406
|
+
case binaryen.LocalGetId: {
|
|
1407
|
+
const value = this.st.locals[v.index];
|
|
1408
|
+
if (!value)
|
|
1409
|
+
return refuse(`local ${v.index} read before it is defined`);
|
|
1410
|
+
if (!this.depth && this.st.gen?.fresh.has(v.index))
|
|
1411
|
+
this.st.gen.read.add(v.index);
|
|
1412
|
+
return value;
|
|
1413
|
+
}
|
|
1414
|
+
case binaryen.LocalSetId: {
|
|
1415
|
+
const value = this.exec(v.value);
|
|
1416
|
+
if (!value)
|
|
1417
|
+
return refuse('local set without a value');
|
|
1418
|
+
if (value.t === 'p')
|
|
1419
|
+
return refuse('a comparison result stored in a local');
|
|
1420
|
+
this.st.locals[v.index] = value;
|
|
1421
|
+
if (!this.depth && this.st.gen) {
|
|
1422
|
+
this.st.gen.fresh.delete(v.index);
|
|
1423
|
+
this.st.gen.written.add(v.index);
|
|
1424
|
+
}
|
|
1425
|
+
return v.isTee ? value : undefined;
|
|
1426
|
+
}
|
|
1427
|
+
case binaryen.ConstId:
|
|
1428
|
+
if (v.type === binaryen.i32)
|
|
1429
|
+
return num(constBits(v));
|
|
1430
|
+
if (v.type === binaryen.i64)
|
|
1431
|
+
return { t: 'd', f: this.ring.konst(BigInt.asUintN(64, constBits(v)), 64) };
|
|
1432
|
+
return refuse('non-integer constant');
|
|
1433
|
+
case binaryen.UnaryId:
|
|
1434
|
+
return this.unary(v);
|
|
1435
|
+
case binaryen.BinaryId:
|
|
1436
|
+
return this.binary(v);
|
|
1437
|
+
case binaryen.LoadId:
|
|
1438
|
+
return this.load(v);
|
|
1439
|
+
case binaryen.StoreId:
|
|
1440
|
+
return this.store(v);
|
|
1441
|
+
case binaryen.IfId: {
|
|
1442
|
+
const taken = this.truth(this.exec(v.condition));
|
|
1443
|
+
if (typeof taken !== 'boolean')
|
|
1444
|
+
throw new Undecided();
|
|
1445
|
+
const arm = taken ? v.ifTrue : v.ifFalse;
|
|
1446
|
+
return arm ? this.exec(arm) : undefined;
|
|
1447
|
+
}
|
|
1448
|
+
case binaryen.SelectId: {
|
|
1449
|
+
const a = this.exec(v.ifTrue);
|
|
1450
|
+
const b = this.exec(v.ifFalse);
|
|
1451
|
+
const taken = this.truth(this.exec(v.condition));
|
|
1452
|
+
if (typeof taken !== 'boolean')
|
|
1453
|
+
throw new Undecided();
|
|
1454
|
+
return taken ? a : b;
|
|
1455
|
+
}
|
|
1456
|
+
case binaryen.CallId:
|
|
1457
|
+
return this.call(v);
|
|
1458
|
+
case binaryen.DropId:
|
|
1459
|
+
this.exec(v.value);
|
|
1460
|
+
return undefined;
|
|
1461
|
+
case binaryen.ReturnId:
|
|
1462
|
+
throw new Jump(RETURN, v.value ? this.exec(v.value) : undefined);
|
|
1463
|
+
case binaryen.UnreachableId:
|
|
1464
|
+
return refuse('unreachable instruction');
|
|
1465
|
+
default:
|
|
1466
|
+
return refuse(`unsupported expression kind ${id}`);
|
|
1467
|
+
}
|
|
1468
|
+
}
|
|
1469
|
+
/** Runs an internal function on the caller's values, inline. */
|
|
1470
|
+
call(v) {
|
|
1471
|
+
if (v.isReturn)
|
|
1472
|
+
return refuse('tail call');
|
|
1473
|
+
if (this.depth >= 8)
|
|
1474
|
+
return refuse('calls nest deeper than eight');
|
|
1475
|
+
const target = this.callee(v.target);
|
|
1476
|
+
if (!target)
|
|
1477
|
+
return refuse(`call to ${v.target}, which is not a defined function`);
|
|
1478
|
+
const args = v.operands.map((o) => this.exec(o));
|
|
1479
|
+
if (args.some((a) => !a || a.t === 'p'))
|
|
1480
|
+
return refuse('call argument is not a value');
|
|
1481
|
+
const frame = target.types.map((type, j) => j < args.length ? args[j] : type === binaryen.i64 ? this.fromConst(64, 0n) : num(0));
|
|
1482
|
+
const outer = this.st.locals;
|
|
1483
|
+
this.st.locals = frame;
|
|
1484
|
+
this.depth++;
|
|
1485
|
+
try {
|
|
1486
|
+
return this.exec(target.body);
|
|
1487
|
+
}
|
|
1488
|
+
catch (error) {
|
|
1489
|
+
if (error instanceof Jump && error.label === RETURN)
|
|
1490
|
+
return error.value;
|
|
1491
|
+
throw error;
|
|
1492
|
+
}
|
|
1493
|
+
finally {
|
|
1494
|
+
this.depth--;
|
|
1495
|
+
this.st.locals = outer;
|
|
1496
|
+
}
|
|
1497
|
+
}
|
|
1498
|
+
truth(v) {
|
|
1499
|
+
if (!v)
|
|
1500
|
+
return refuse('branch on a missing value');
|
|
1501
|
+
if (v.t === 'p')
|
|
1502
|
+
return v;
|
|
1503
|
+
if (v.t === 'd') {
|
|
1504
|
+
const c = this.ring.asConst(v.f);
|
|
1505
|
+
return c !== undefined ? c !== 0n : refuse('branch on data');
|
|
1506
|
+
}
|
|
1507
|
+
if (isNum(v))
|
|
1508
|
+
return v.c !== 0n;
|
|
1509
|
+
const r = decide('ne', v, num(0), this.ranges);
|
|
1510
|
+
return r.t === 'c' ? r.c !== 0n : r;
|
|
1511
|
+
}
|
|
1512
|
+
constOf(v) {
|
|
1513
|
+
if (v.t === 'c')
|
|
1514
|
+
return isNum(v) ? { bits: 32, v: u32(v.c) } : undefined;
|
|
1515
|
+
if (v.t === 'd') {
|
|
1516
|
+
const c = this.ring.asConst(v.f);
|
|
1517
|
+
return c === undefined ? undefined : { bits: v.f.w, v: c };
|
|
1518
|
+
}
|
|
1519
|
+
return undefined;
|
|
1520
|
+
}
|
|
1521
|
+
fromConst(bits, v) {
|
|
1522
|
+
return bits === 32 ? num(v) : { t: 'd', f: this.ring.konst(v, 64) };
|
|
1523
|
+
}
|
|
1524
|
+
dataOf(v, bits) {
|
|
1525
|
+
if (v.t === 'd')
|
|
1526
|
+
return v.f;
|
|
1527
|
+
if (v.t === 'c' && isNum(v) && bits === 32)
|
|
1528
|
+
return this.ring.konst(u32(v.c), 32);
|
|
1529
|
+
return refuse('a control value used as data');
|
|
1530
|
+
}
|
|
1531
|
+
unary(v) {
|
|
1532
|
+
const k = UNARY.get(v.op) ?? refuse(`unsupported operation ${v.op}`);
|
|
1533
|
+
const a = this.exec(v.value);
|
|
1534
|
+
if (!a)
|
|
1535
|
+
return refuse('operand without a value');
|
|
1536
|
+
const c = this.constOf(a);
|
|
1537
|
+
if (c) {
|
|
1538
|
+
const r = evalUnary(k.op, c.bits, c.v);
|
|
1539
|
+
return k.op === 'EqZ' ? num(r) : this.fromConst(k.bits, r);
|
|
1540
|
+
}
|
|
1541
|
+
if (k.op === 'EqZ') {
|
|
1542
|
+
if (a.t === 'p')
|
|
1543
|
+
return { t: 'p', rel: negate(a.rel), a: a.a, b: a.b };
|
|
1544
|
+
if (a.t === 'c')
|
|
1545
|
+
return decide('eq', a, num(0), this.ranges);
|
|
1546
|
+
}
|
|
1547
|
+
if (a.t !== 'd')
|
|
1548
|
+
return refuse(`${k.op} of a control value`);
|
|
1549
|
+
return { t: 'd', f: this.ring.unary(k.op, a.f) };
|
|
1550
|
+
}
|
|
1551
|
+
binary(v) {
|
|
1552
|
+
const k = BINARY.get(v.op) ?? refuse(`unsupported operation ${v.op}`);
|
|
1553
|
+
if (k.op === 'And') {
|
|
1554
|
+
const parity = this.parity(v);
|
|
1555
|
+
if (parity)
|
|
1556
|
+
return parity;
|
|
1557
|
+
}
|
|
1558
|
+
const a = this.exec(v.left);
|
|
1559
|
+
const b = this.exec(v.right);
|
|
1560
|
+
if (!a || !b)
|
|
1561
|
+
return refuse('operand without a value');
|
|
1562
|
+
const ca = this.constOf(a);
|
|
1563
|
+
const cb = this.constOf(b);
|
|
1564
|
+
if (ca && cb) {
|
|
1565
|
+
const r = evalBinary(k.op, k.bits, ca.v, cb.v);
|
|
1566
|
+
return COMPARE.has(k.op) ? num(r) : this.fromConst(k.bits, r);
|
|
1567
|
+
}
|
|
1568
|
+
if (a.t === 'p' || b.t === 'p')
|
|
1569
|
+
return refuse('operation on a comparison result');
|
|
1570
|
+
if (a.t === 'c' && b.t === 'c')
|
|
1571
|
+
return this.controlBinary(k.op, a, b);
|
|
1572
|
+
return {
|
|
1573
|
+
t: 'd',
|
|
1574
|
+
f: this.ring.binary(k.op, this.dataOf(a, k.bits), this.dataOf(b, k.bits))
|
|
1575
|
+
};
|
|
1576
|
+
}
|
|
1577
|
+
/** popcnt(x) & 1 over data, which the generic rules would refuse because the count is not affine. */
|
|
1578
|
+
parity(v) {
|
|
1579
|
+
for (const [count, one] of [
|
|
1580
|
+
[v.left, v.right],
|
|
1581
|
+
[v.right, v.left]
|
|
1582
|
+
]) {
|
|
1583
|
+
if (binaryen.getExpressionId(count) !== binaryen.UnaryId)
|
|
1584
|
+
continue;
|
|
1585
|
+
if (binaryen.getExpressionId(one) !== binaryen.ConstId)
|
|
1586
|
+
continue;
|
|
1587
|
+
const u = info(count);
|
|
1588
|
+
const c = info(one);
|
|
1589
|
+
if (UNARY.get(u.op)?.op !== 'Popcnt' || constBits(c) !== 1n)
|
|
1590
|
+
continue;
|
|
1591
|
+
const x = this.exec(u.value);
|
|
1592
|
+
if (!x)
|
|
1593
|
+
return refuse('operand without a value');
|
|
1594
|
+
const cx = this.constOf(x);
|
|
1595
|
+
if (cx)
|
|
1596
|
+
return this.fromConst(cx.bits, evalUnary('Popcnt', cx.bits, cx.v) & 1n);
|
|
1597
|
+
if (x.t !== 'd')
|
|
1598
|
+
return refuse('population count of a control value');
|
|
1599
|
+
return { t: 'd', f: this.ring.parity(x.f) };
|
|
1600
|
+
}
|
|
1601
|
+
return undefined;
|
|
1602
|
+
}
|
|
1603
|
+
controlBinary(op, a, b) {
|
|
1604
|
+
switch (op) {
|
|
1605
|
+
case 'Add':
|
|
1606
|
+
return cadd(a, b);
|
|
1607
|
+
case 'Sub':
|
|
1608
|
+
return csub(a, b);
|
|
1609
|
+
case 'Mul':
|
|
1610
|
+
if (isNum(b))
|
|
1611
|
+
return scale(a, b.c);
|
|
1612
|
+
if (isNum(a))
|
|
1613
|
+
return scale(b, a.c);
|
|
1614
|
+
return refuse('product of two control values');
|
|
1615
|
+
case 'Shl':
|
|
1616
|
+
if (isNum(b))
|
|
1617
|
+
return scale(a, 1n << (u32(b.c) & 31n));
|
|
1618
|
+
return refuse('shift by a control value');
|
|
1619
|
+
case 'And':
|
|
1620
|
+
if (isNum(b))
|
|
1621
|
+
return maskControl(a, u32(b.c));
|
|
1622
|
+
if (isNum(a))
|
|
1623
|
+
return maskControl(b, u32(a.c));
|
|
1624
|
+
return refuse('and of two control values');
|
|
1625
|
+
case 'ShrU':
|
|
1626
|
+
if (isNum(b))
|
|
1627
|
+
return this.shiftRight(a, Number(u32(b.c) & 31n));
|
|
1628
|
+
return refuse('shift by a control value');
|
|
1629
|
+
case 'Eq':
|
|
1630
|
+
return decide('eq', a, b, this.ranges);
|
|
1631
|
+
case 'Ne':
|
|
1632
|
+
return decide('ne', a, b, this.ranges);
|
|
1633
|
+
case 'LtU':
|
|
1634
|
+
return decide('ltu', a, b, this.ranges);
|
|
1635
|
+
case 'LeU':
|
|
1636
|
+
return decide('leu', a, b, this.ranges);
|
|
1637
|
+
case 'GtU':
|
|
1638
|
+
return decide('gtu', a, b, this.ranges);
|
|
1639
|
+
case 'GeU':
|
|
1640
|
+
return decide('geu', a, b, this.ranges);
|
|
1641
|
+
default:
|
|
1642
|
+
return refuse(`${op} of control values`);
|
|
1643
|
+
}
|
|
1644
|
+
}
|
|
1645
|
+
shiftRight(a, s) {
|
|
1646
|
+
if (s === 0)
|
|
1647
|
+
return a;
|
|
1648
|
+
if (!nowrap(a, this.ranges))
|
|
1649
|
+
return refuse('shift of a value that may wrap');
|
|
1650
|
+
const d = 1n << BigInt(s);
|
|
1651
|
+
const terms = new Map();
|
|
1652
|
+
for (const [k, v] of a.s) {
|
|
1653
|
+
if (v % d !== 0n)
|
|
1654
|
+
return refuse('shift of a value with low bits set');
|
|
1655
|
+
terms.set(k, v / d);
|
|
1656
|
+
}
|
|
1657
|
+
return norm(floorDiv(a.c, d), terms);
|
|
1658
|
+
}
|
|
1659
|
+
load(v) {
|
|
1660
|
+
if (v.isAtomic)
|
|
1661
|
+
return refuse('atomic load');
|
|
1662
|
+
if (v.type !== binaryen.i32 && v.type !== binaryen.i64)
|
|
1663
|
+
return refuse('non-integer load');
|
|
1664
|
+
const bits = v.type === binaryen.i64 ? 64 : 32;
|
|
1665
|
+
const width = v.bytes;
|
|
1666
|
+
const addr = this.exec(v.ptr);
|
|
1667
|
+
if (!addr || addr.t === 'p')
|
|
1668
|
+
return refuse('load address is not a value');
|
|
1669
|
+
const offset = imm32(v);
|
|
1670
|
+
if (addr.t === 'd') {
|
|
1671
|
+
if (v.isSigned)
|
|
1672
|
+
return refuse('signed table load');
|
|
1673
|
+
const read = (a, wd) => this.st.mem.read(a, wd);
|
|
1674
|
+
return { t: 'd', f: this.ring.lookup(addr.f, Number(offset), width, bits, read) };
|
|
1675
|
+
}
|
|
1676
|
+
if (isNum(addr)) {
|
|
1677
|
+
let x = this.st.mem.read(Number(u32(addr.c) + offset), width);
|
|
1678
|
+
if (v.isSigned)
|
|
1679
|
+
x = BigInt.asUintN(bits, BigInt.asIntN(8 * width, x));
|
|
1680
|
+
return this.fromConst(bits, x);
|
|
1681
|
+
}
|
|
1682
|
+
const address = cadd(addr, num(offset));
|
|
1683
|
+
const gen = this.st.gen;
|
|
1684
|
+
if (gen) {
|
|
1685
|
+
if (gen.loads.length >= 64)
|
|
1686
|
+
return refuse('more than 64 input loads in one iteration');
|
|
1687
|
+
gen.loads.push({ address, width, imm: offset });
|
|
1688
|
+
gen.touches.push({ store: false, address, width });
|
|
1689
|
+
return this.extended(v, this.ring.bytes(PH + 8 * (gen.loads.length - 1), width, bits));
|
|
1690
|
+
}
|
|
1691
|
+
const pos = csub(address, this.st.base);
|
|
1692
|
+
if (!isNum(pos) || pos.c < 0n || pos.c + BigInt(width) > MAXPOS)
|
|
1693
|
+
return refuse('input load not at a fixed offset from the first unfolded byte');
|
|
1694
|
+
// the address wraps at 2^32 but the immediate does not, so the two agree only when the position covers it
|
|
1695
|
+
if (offset > pos.c)
|
|
1696
|
+
return refuse('a load whose immediate offset exceeds its position');
|
|
1697
|
+
const at = csub(address, sym('P0'));
|
|
1698
|
+
for (const w of this.st.written)
|
|
1699
|
+
if (!this.apart(at, width, w))
|
|
1700
|
+
return refuse('an input byte is read after the call wrote it');
|
|
1701
|
+
this.ensurePre();
|
|
1702
|
+
const c = Number(pos.c);
|
|
1703
|
+
this.st.pending = Math.max(this.st.pending, c + width);
|
|
1704
|
+
return this.extended(v, this.ring.bytes(c, width, bits));
|
|
1705
|
+
}
|
|
1706
|
+
/** Applies the sign extension of a signed load to the zero-extended bytes. */
|
|
1707
|
+
extended(v, loaded) {
|
|
1708
|
+
const bits = v.type === binaryen.i64 ? 64 : 32;
|
|
1709
|
+
const extend = { 1: 'Extend8S', 2: 'Extend16S', 4: 'Extend32S' }[v.bytes];
|
|
1710
|
+
if (!v.isSigned || !extend || v.bytes * 8 === bits)
|
|
1711
|
+
return { t: 'd', f: loaded };
|
|
1712
|
+
return { t: 'd', f: this.ring.unary(extend, loaded) };
|
|
1713
|
+
}
|
|
1714
|
+
/** Whether `width` bytes at offset `at` from the pointer lie wholly outside the run `w`. */
|
|
1715
|
+
apart(at, width, w) {
|
|
1716
|
+
const signed = (a) => (isNum(a) ? [a.c, a.c] : span(a, this.ranges));
|
|
1717
|
+
if (signed(csub(cadd(at, num(width)), w.start))[1] <= 0n)
|
|
1718
|
+
return true;
|
|
1719
|
+
return signed(csub(at, cadd(w.start, w.length)))[0] >= 0n;
|
|
1720
|
+
}
|
|
1721
|
+
store(v) {
|
|
1722
|
+
if (v.isAtomic)
|
|
1723
|
+
return refuse('atomic store');
|
|
1724
|
+
const addr = this.exec(v.ptr);
|
|
1725
|
+
const value = this.exec(v.value);
|
|
1726
|
+
if (!addr || addr.t === 'p' || !value || value.t === 'p')
|
|
1727
|
+
return refuse('store operand is not a value');
|
|
1728
|
+
if (addr.t === 'c' && isNum(addr)) {
|
|
1729
|
+
if (!this.allowStore || this.st.gen)
|
|
1730
|
+
return refuse('store to memory');
|
|
1731
|
+
const cv = this.constOf(value);
|
|
1732
|
+
if (!cv)
|
|
1733
|
+
return refuse('store that depends on the input or the state');
|
|
1734
|
+
this.st.mem.write(Number(u32(addr.c) + imm32(v)), v.bytes, cv.v);
|
|
1735
|
+
return undefined;
|
|
1736
|
+
}
|
|
1737
|
+
return this.output(v, addr, value);
|
|
1738
|
+
}
|
|
1739
|
+
/** The low byte of a stored value, as a form. */
|
|
1740
|
+
byteOf(value) {
|
|
1741
|
+
const f = this.dataOf(value, value.t === 'd' ? value.f.w : 32);
|
|
1742
|
+
return this.ring.binary('And', f, this.ring.konst(255n, f.w));
|
|
1743
|
+
}
|
|
1744
|
+
/**
|
|
1745
|
+
* A byte stored at an address that follows the pointer. In a loop it is kept for `summarize`;
|
|
1746
|
+
* otherwise it must be the byte transform of the state before it, which the one byte call defines.
|
|
1747
|
+
*/
|
|
1748
|
+
output(v, addr, value) {
|
|
1749
|
+
if (v.bytes !== 1)
|
|
1750
|
+
return refuse('a store of more than one byte');
|
|
1751
|
+
if (addr.t !== 'c')
|
|
1752
|
+
return refuse('store address is data');
|
|
1753
|
+
const address = cadd(addr, num(imm32(v)));
|
|
1754
|
+
const form = this.byteOf(value);
|
|
1755
|
+
const gen = this.st.gen;
|
|
1756
|
+
if (gen) {
|
|
1757
|
+
if (gen.stores.length >= 64)
|
|
1758
|
+
return refuse('more than 64 stores in one iteration');
|
|
1759
|
+
gen.stores.push({ address, value: form, imm: imm32(v) });
|
|
1760
|
+
gen.touches.push({ store: true, address, width: 1 });
|
|
1761
|
+
return undefined;
|
|
1762
|
+
}
|
|
1763
|
+
const pos = csub(address, this.st.base);
|
|
1764
|
+
if (!isNum(pos) || pos.c < 0n || pos.c >= MAXPOS)
|
|
1765
|
+
return refuse('store not at a fixed offset from the first unfolded byte');
|
|
1766
|
+
if (imm32(v) > pos.c)
|
|
1767
|
+
return refuse('a store whose immediate offset exceeds its position');
|
|
1768
|
+
this.ensurePre();
|
|
1769
|
+
const c = Number(pos.c);
|
|
1770
|
+
if (this.out1) {
|
|
1771
|
+
if (!this.ring.equal(form, this.ring.subst(this.out1, this.iterate(c), c)))
|
|
1772
|
+
return refuse('a stored byte is not the byte transform of the state before it');
|
|
1773
|
+
}
|
|
1774
|
+
else if (!this.recording)
|
|
1775
|
+
return refuse('a store before the one byte output is known');
|
|
1776
|
+
this.st.written.push({ start: csub(address, sym('P0')), length: num(1), form });
|
|
1777
|
+
return undefined;
|
|
1778
|
+
}
|
|
1779
|
+
ensurePre() {
|
|
1780
|
+
if (this.st.pre)
|
|
1781
|
+
return;
|
|
1782
|
+
const pre = new Map();
|
|
1783
|
+
this.st.locals.forEach((value, j) => {
|
|
1784
|
+
if (value?.t !== 'd')
|
|
1785
|
+
return;
|
|
1786
|
+
if (this.ring.positions(value.f).length)
|
|
1787
|
+
refuse('state mixed with input bytes');
|
|
1788
|
+
pre.set(j, value.f);
|
|
1789
|
+
});
|
|
1790
|
+
this.st.pre = pre;
|
|
1791
|
+
}
|
|
1792
|
+
iterate(k) {
|
|
1793
|
+
const cached = this.iterated.get(k);
|
|
1794
|
+
if (cached)
|
|
1795
|
+
return cached;
|
|
1796
|
+
if (!this.f1)
|
|
1797
|
+
return refuse('no one byte form yet');
|
|
1798
|
+
const f = k === 0
|
|
1799
|
+
? this.ring.state(this.w)
|
|
1800
|
+
: this.ring.subst(this.f1, this.iterate(k - 1), k - 1);
|
|
1801
|
+
this.iterated.set(k, f);
|
|
1802
|
+
return f;
|
|
1803
|
+
}
|
|
1804
|
+
snapshot() {
|
|
1805
|
+
const s = this.st;
|
|
1806
|
+
return {
|
|
1807
|
+
locals: [...s.locals],
|
|
1808
|
+
base: s.base,
|
|
1809
|
+
pending: s.pending,
|
|
1810
|
+
pre: s.pre && new Map(s.pre),
|
|
1811
|
+
mem: s.mem.clone(),
|
|
1812
|
+
gen: undefined,
|
|
1813
|
+
written: [...s.written]
|
|
1814
|
+
};
|
|
1815
|
+
}
|
|
1816
|
+
// #endregion
|
|
1817
|
+
// #region loops
|
|
1818
|
+
loop(v) {
|
|
1819
|
+
if (v.type !== binaryen.none && v.type !== binaryen.unreachable)
|
|
1820
|
+
return refuse('loop with a result');
|
|
1821
|
+
const saved = this.snapshot();
|
|
1822
|
+
const nested = this.st.gen !== undefined;
|
|
1823
|
+
try {
|
|
1824
|
+
for (let i = 0;; i++) {
|
|
1825
|
+
if (i > 4096)
|
|
1826
|
+
throw new Undecided();
|
|
1827
|
+
try {
|
|
1828
|
+
this.exec(v.body);
|
|
1829
|
+
return undefined;
|
|
1830
|
+
}
|
|
1831
|
+
catch (error) {
|
|
1832
|
+
if (error instanceof Jump && error.label === v.name)
|
|
1833
|
+
continue;
|
|
1834
|
+
throw error;
|
|
1835
|
+
}
|
|
1836
|
+
}
|
|
1837
|
+
}
|
|
1838
|
+
catch (error) {
|
|
1839
|
+
if (!(error instanceof Undecided))
|
|
1840
|
+
throw error;
|
|
1841
|
+
if (nested)
|
|
1842
|
+
return refuse('a counted loop inside a counted loop');
|
|
1843
|
+
this.st = saved;
|
|
1844
|
+
this.summarize(v);
|
|
1845
|
+
return undefined;
|
|
1846
|
+
}
|
|
1847
|
+
}
|
|
1848
|
+
/** The effect of a counted loop whose length depends on the quotient, by induction over its iterations. */
|
|
1849
|
+
summarize(loop) {
|
|
1850
|
+
const outer = this.st;
|
|
1851
|
+
if (outer.gen || this.depth)
|
|
1852
|
+
return refuse('a counted loop inside a counted loop or a call');
|
|
1853
|
+
const ring = this.ring;
|
|
1854
|
+
const bodyInfo = info(loop.body);
|
|
1855
|
+
const stmts = bodyInfo.id === binaryen.BlockId && !bodyInfo.name ? bodyInfo.children : [loop.body];
|
|
1856
|
+
const last = info(stmts[stmts.length - 1]);
|
|
1857
|
+
let head;
|
|
1858
|
+
let tail;
|
|
1859
|
+
let exitLabel = '';
|
|
1860
|
+
let work;
|
|
1861
|
+
if (last.id === binaryen.BreakId &&
|
|
1862
|
+
last.name === loop.name &&
|
|
1863
|
+
last.condition &&
|
|
1864
|
+
!last.value) {
|
|
1865
|
+
tail = last.condition;
|
|
1866
|
+
work = stmts.slice(0, -1);
|
|
1867
|
+
}
|
|
1868
|
+
else if (last.id === binaryen.BreakId && last.name === loop.name && !last.condition) {
|
|
1869
|
+
const first = info(stmts[0]);
|
|
1870
|
+
if (first.id !== binaryen.BreakId || !first.condition || first.name === loop.name)
|
|
1871
|
+
return refuse('loop has no test at its head or its tail');
|
|
1872
|
+
head = first.condition;
|
|
1873
|
+
exitLabel = first.name;
|
|
1874
|
+
work = stmts.slice(1, -1);
|
|
1875
|
+
}
|
|
1876
|
+
else
|
|
1877
|
+
return refuse('loop does not end in its back edge');
|
|
1878
|
+
this.ensurePre();
|
|
1879
|
+
const pre = outer.pre;
|
|
1880
|
+
const heads = new Map();
|
|
1881
|
+
const writes = new Set();
|
|
1882
|
+
for (const s of [head, tail, ...work])
|
|
1883
|
+
if (s !== undefined)
|
|
1884
|
+
assigned(s, writes);
|
|
1885
|
+
const generic = outer.locals.map((value, j) => {
|
|
1886
|
+
if (!value)
|
|
1887
|
+
return undefined;
|
|
1888
|
+
// a local the loop never sets keeps its value, so its constants and bounds stay exact
|
|
1889
|
+
if (!writes.has(j) && value.t === 'c')
|
|
1890
|
+
return value;
|
|
1891
|
+
if (!writes.has(j) &&
|
|
1892
|
+
value.t === 'd' &&
|
|
1893
|
+
stateFree(value.f) &&
|
|
1894
|
+
!ring.positions(value.f).length)
|
|
1895
|
+
return value;
|
|
1896
|
+
if (value.t === 'c') {
|
|
1897
|
+
heads.set(j, `h${j}`);
|
|
1898
|
+
return sym(`h${j}`);
|
|
1899
|
+
}
|
|
1900
|
+
if (value.t === 'd') {
|
|
1901
|
+
const f = pre.get(j);
|
|
1902
|
+
return f ? { t: 'd', f } : undefined;
|
|
1903
|
+
}
|
|
1904
|
+
return refuse('a comparison held in a local across a loop');
|
|
1905
|
+
});
|
|
1906
|
+
const gen = {
|
|
1907
|
+
loads: [],
|
|
1908
|
+
stores: [],
|
|
1909
|
+
touches: [],
|
|
1910
|
+
fresh: new Set(generic.keys()),
|
|
1911
|
+
read: new Set(),
|
|
1912
|
+
written: new Set()
|
|
1913
|
+
};
|
|
1914
|
+
this.st = {
|
|
1915
|
+
locals: generic,
|
|
1916
|
+
base: outer.base,
|
|
1917
|
+
pending: 0,
|
|
1918
|
+
pre,
|
|
1919
|
+
mem: outer.mem.clone(),
|
|
1920
|
+
gen,
|
|
1921
|
+
written: []
|
|
1922
|
+
};
|
|
1923
|
+
let cond;
|
|
1924
|
+
try {
|
|
1925
|
+
if (head !== undefined)
|
|
1926
|
+
cond = this.exec(head);
|
|
1927
|
+
for (const s of work)
|
|
1928
|
+
this.exec(s);
|
|
1929
|
+
if (tail !== undefined)
|
|
1930
|
+
cond = this.exec(tail);
|
|
1931
|
+
}
|
|
1932
|
+
catch (error) {
|
|
1933
|
+
if (error instanceof Undecided)
|
|
1934
|
+
return refuse('a branch inside a counted loop is undecided');
|
|
1935
|
+
if (error instanceof Jump)
|
|
1936
|
+
return refuse('a branch leaves a counted loop');
|
|
1937
|
+
throw error;
|
|
1938
|
+
}
|
|
1939
|
+
finally {
|
|
1940
|
+
this.st = outer;
|
|
1941
|
+
}
|
|
1942
|
+
const end = generic;
|
|
1943
|
+
this.loops++;
|
|
1944
|
+
if (!gen.loads.length)
|
|
1945
|
+
return refuse('counted loop with no input loads');
|
|
1946
|
+
const symbolsIn = (value) => !value
|
|
1947
|
+
? []
|
|
1948
|
+
: value.t === 'c'
|
|
1949
|
+
? [...value.s.keys()]
|
|
1950
|
+
: value.t === 'p'
|
|
1951
|
+
? [...value.a.s.keys(), ...value.b.s.keys()]
|
|
1952
|
+
: [];
|
|
1953
|
+
const usedByOthers = (name, except) => gen.loads.some((l) => l.address.s.has(name)) ||
|
|
1954
|
+
symbolsIn(cond).includes(name) ||
|
|
1955
|
+
end.some((value, j) => j !== except && symbolsIn(value).includes(name));
|
|
1956
|
+
const init = (j) => outer.locals[j];
|
|
1957
|
+
const delta = new Map();
|
|
1958
|
+
const temps = new Set();
|
|
1959
|
+
for (const [j, name] of heads) {
|
|
1960
|
+
const value = end[j];
|
|
1961
|
+
if (value?.t === 'c') {
|
|
1962
|
+
const d = csub(value, sym(name));
|
|
1963
|
+
if (isNum(d)) {
|
|
1964
|
+
delta.set(j, d.c);
|
|
1965
|
+
continue;
|
|
1966
|
+
}
|
|
1967
|
+
}
|
|
1968
|
+
if (usedByOthers(name, j) || (value?.t === 'c' && value.s.has(name)))
|
|
1969
|
+
return refuse(`local ${j} does not change by a fixed step`);
|
|
1970
|
+
temps.add(j);
|
|
1971
|
+
}
|
|
1972
|
+
const step = new Map();
|
|
1973
|
+
for (const [j, name] of heads)
|
|
1974
|
+
if (delta.has(j))
|
|
1975
|
+
step.set(name, cadd(init(j), scale(sym('t'), delta.get(j))));
|
|
1976
|
+
const base1 = cadd(outer.base, num(outer.pending));
|
|
1977
|
+
let stride;
|
|
1978
|
+
const positions = [];
|
|
1979
|
+
for (const l of gen.loads) {
|
|
1980
|
+
const a = substCtl(l.address, step);
|
|
1981
|
+
const alpha = a.s.get('t') ?? 0n;
|
|
1982
|
+
if (stride === undefined)
|
|
1983
|
+
stride = alpha;
|
|
1984
|
+
else if (stride !== alpha)
|
|
1985
|
+
return refuse('loads advance by different strides');
|
|
1986
|
+
const c = csub(csub(a, scale(sym('t'), alpha)), base1);
|
|
1987
|
+
if (!isNum(c) || c.c < 0n || c.c + BigInt(l.width) > alpha)
|
|
1988
|
+
return refuse('a load falls outside its iteration window');
|
|
1989
|
+
if (l.imm > c.c)
|
|
1990
|
+
return refuse('a load whose immediate offset exceeds its position');
|
|
1991
|
+
positions.push(Number(c.c));
|
|
1992
|
+
}
|
|
1993
|
+
if (stride === undefined || stride < 1n || stride > 64n)
|
|
1994
|
+
return refuse('stride out of range');
|
|
1995
|
+
const live = [...gen.read].filter((j) => outer.locals[j]?.t === 'd' && pre.has(j));
|
|
1996
|
+
for (const j of live) {
|
|
1997
|
+
const have = outer.locals[j].f;
|
|
1998
|
+
const want = outer.pending === 0
|
|
1999
|
+
? pre.get(j)
|
|
2000
|
+
: ring.subst(pre.get(j), this.iterate(outer.pending), 0);
|
|
2001
|
+
if (!ring.equal(have, want))
|
|
2002
|
+
return refuse('state at the loop is not the folded prefix');
|
|
2003
|
+
}
|
|
2004
|
+
const rename = new Map();
|
|
2005
|
+
gen.loads.forEach((l, i) => {
|
|
2006
|
+
for (let b = 0; b < l.width; b++)
|
|
2007
|
+
rename.set(PH + 8 * i + b, positions[i] + b);
|
|
2008
|
+
});
|
|
2009
|
+
for (const j of live) {
|
|
2010
|
+
let value = end[j];
|
|
2011
|
+
// a step that ignores the state leaves a constant, which is a form with no variables
|
|
2012
|
+
if (value?.t === 'c' && isNum(value) && pre.get(j).w === 32)
|
|
2013
|
+
value = { t: 'd', f: ring.konst(u32(value.c), 32) };
|
|
2014
|
+
if (value?.t !== 'd')
|
|
2015
|
+
return refuse('a state local stops holding data');
|
|
2016
|
+
const got = ring.remap(value.f, rename);
|
|
2017
|
+
const want = ring.subst(pre.get(j), this.iterate(Number(stride)), 0);
|
|
2018
|
+
if (!ring.equal(got, want))
|
|
2019
|
+
return refuse('loop body is not the byte step applied per iteration');
|
|
2020
|
+
}
|
|
2021
|
+
if (gen.stores.length) {
|
|
2022
|
+
if (!this.out1)
|
|
2023
|
+
return refuse('a store in a loop before the one byte output is known');
|
|
2024
|
+
const window = (address, width) => {
|
|
2025
|
+
const a = substCtl(address, step);
|
|
2026
|
+
if ((a.s.get('t') ?? 0n) !== stride)
|
|
2027
|
+
return refuse('a store advances by another stride');
|
|
2028
|
+
const c = csub(csub(a, scale(sym('t'), stride)), base1);
|
|
2029
|
+
if (!isNum(c) || c.c < 0n || c.c + BigInt(width) > stride)
|
|
2030
|
+
return refuse('a store falls outside its iteration window');
|
|
2031
|
+
return Number(c.c);
|
|
2032
|
+
};
|
|
2033
|
+
const where = gen.stores.map((s) => {
|
|
2034
|
+
const c = window(s.address, 1);
|
|
2035
|
+
if (s.imm > BigInt(c))
|
|
2036
|
+
return refuse('a store whose immediate offset exceeds its position');
|
|
2037
|
+
return c;
|
|
2038
|
+
});
|
|
2039
|
+
if (where.length !== Number(stride) || new Set(where).size !== where.length)
|
|
2040
|
+
return refuse('the stores of one iteration do not write each byte of its window once');
|
|
2041
|
+
gen.stores.forEach((s, k) => {
|
|
2042
|
+
const got = ring.remap(s.value, rename);
|
|
2043
|
+
const want = ring.subst(this.out1, this.iterate(where[k]), where[k]);
|
|
2044
|
+
if (!ring.equal(got, want))
|
|
2045
|
+
refuse('a stored byte is not the byte transform of the state before it');
|
|
2046
|
+
});
|
|
2047
|
+
const spots = gen.touches.map((t) => ({ ...t, at: window(t.address, t.width) }));
|
|
2048
|
+
spots.forEach((s, i) => {
|
|
2049
|
+
if (!s.store)
|
|
2050
|
+
return;
|
|
2051
|
+
for (const l of spots.slice(i + 1))
|
|
2052
|
+
if (!l.store && l.at < s.at + s.width && s.at < l.at + l.width)
|
|
2053
|
+
refuse('an input byte is read after the loop wrote it');
|
|
2054
|
+
});
|
|
2055
|
+
}
|
|
2056
|
+
// a state copy written in the loop that equals a live local's next value holds that local's form afterwards
|
|
2057
|
+
const copies = new Map();
|
|
2058
|
+
for (const j of gen.written) {
|
|
2059
|
+
const value = end[j];
|
|
2060
|
+
if (value?.t !== 'd' || live.includes(j))
|
|
2061
|
+
continue;
|
|
2062
|
+
const got = ring.remap(value.f, rename);
|
|
2063
|
+
for (const form of pre.values())
|
|
2064
|
+
if (ring.equal(got, ring.subst(form, this.iterate(Number(stride)), 0))) {
|
|
2065
|
+
copies.set(j, form);
|
|
2066
|
+
break;
|
|
2067
|
+
}
|
|
2068
|
+
}
|
|
2069
|
+
const trips = this.trips(cond, tail !== undefined, step);
|
|
2070
|
+
const T = tail !== undefined ? cadd(trips, num(1)) : trips;
|
|
2071
|
+
if (span(T, this.ranges)[0] < (tail !== undefined ? 1n : 0n))
|
|
2072
|
+
return refuse('loop trip count may be negative');
|
|
2073
|
+
// the bytes the loop covers are computed as a form that wraps at 2^32, so they must not reach it
|
|
2074
|
+
if (span(T, this.ranges)[1] * stride > M32)
|
|
2075
|
+
return refuse('loop covers more than 2^32 bytes');
|
|
2076
|
+
const before = tail !== undefined ? csub(T, num(1)) : undefined;
|
|
2077
|
+
const lastStep = new Map();
|
|
2078
|
+
if (before)
|
|
2079
|
+
for (const [j, name] of heads)
|
|
2080
|
+
if (delta.has(j))
|
|
2081
|
+
lastStep.set(name, cadd(init(j), scale(before, delta.get(j))));
|
|
2082
|
+
const locals = [...outer.locals];
|
|
2083
|
+
end.forEach((value, j) => {
|
|
2084
|
+
if (heads.has(j) && delta.has(j)) {
|
|
2085
|
+
locals[j] = cadd(init(j), scale(T, delta.get(j)));
|
|
2086
|
+
}
|
|
2087
|
+
else if (live.includes(j)) {
|
|
2088
|
+
locals[j] = { t: 'd', f: pre.get(j) };
|
|
2089
|
+
}
|
|
2090
|
+
else if (copies.has(j) && span(T, this.ranges)[0] >= 1n) {
|
|
2091
|
+
locals[j] = { t: 'd', f: copies.get(j) };
|
|
2092
|
+
}
|
|
2093
|
+
else if (value?.t === 'c' && before && gen.written.has(j)) {
|
|
2094
|
+
locals[j] = substCtl(value, lastStep);
|
|
2095
|
+
}
|
|
2096
|
+
else if (gen.written.has(j) ||
|
|
2097
|
+
heads.has(j) ||
|
|
2098
|
+
(outer.locals[j]?.t === 'd' && !this.keeps(outer.locals[j], writes.has(j)))) {
|
|
2099
|
+
locals[j] = undefined;
|
|
2100
|
+
}
|
|
2101
|
+
});
|
|
2102
|
+
this.st = {
|
|
2103
|
+
locals,
|
|
2104
|
+
base: cadd(base1, scale(T, stride)),
|
|
2105
|
+
pending: 0,
|
|
2106
|
+
pre,
|
|
2107
|
+
mem: outer.mem,
|
|
2108
|
+
gen: undefined,
|
|
2109
|
+
written: gen.stores.length
|
|
2110
|
+
? [...outer.written, { start: csub(base1, sym('P0')), length: scale(T, stride) }]
|
|
2111
|
+
: outer.written
|
|
2112
|
+
};
|
|
2113
|
+
if (head !== undefined)
|
|
2114
|
+
throw new Jump(exitLabel, undefined);
|
|
2115
|
+
}
|
|
2116
|
+
/** Whether a data local that the loop does not set still holds its value afterwards. */
|
|
2117
|
+
keeps(value, set) {
|
|
2118
|
+
return !set && stateFree(value.f) && !this.ring.positions(value.f).length;
|
|
2119
|
+
}
|
|
2120
|
+
/** The number of iterations of the loop, as a form over the quotient. */
|
|
2121
|
+
trips(cond, tail, step) {
|
|
2122
|
+
if (!cond || cond.t === 'd')
|
|
2123
|
+
return refuse('loop test is not a control value');
|
|
2124
|
+
let rel;
|
|
2125
|
+
let a;
|
|
2126
|
+
let b;
|
|
2127
|
+
if (cond.t === 'p')
|
|
2128
|
+
[rel, a, b] = [cond.rel, cond.a, cond.b];
|
|
2129
|
+
else
|
|
2130
|
+
[rel, a, b] = ['ne', cond, num(0)];
|
|
2131
|
+
const exit = tail ? negate(rel) : rel;
|
|
2132
|
+
a = substCtl(a, step);
|
|
2133
|
+
b = substCtl(b, step);
|
|
2134
|
+
const d = csub(a, b);
|
|
2135
|
+
const slope = d.s.get('t') ?? 0n;
|
|
2136
|
+
const d0 = norm(d.c, new Map([...d.s].filter(([k]) => k !== 't')));
|
|
2137
|
+
for (const k of d0.s.keys())
|
|
2138
|
+
if (k !== 'Q')
|
|
2139
|
+
return refuse('loop test depends on the pointer');
|
|
2140
|
+
const [lo0, hi0] = span(d0, this.ranges);
|
|
2141
|
+
if (lo0 <= -(1n << 32n) || hi0 >= 1n << 32n)
|
|
2142
|
+
return refuse('loop test may wrap');
|
|
2143
|
+
let first;
|
|
2144
|
+
if (exit === 'eq') {
|
|
2145
|
+
if (slope === 0n) {
|
|
2146
|
+
if (!(isNum(d0) && d0.c === 0n))
|
|
2147
|
+
return refuse('loop test never changes');
|
|
2148
|
+
first = num(0);
|
|
2149
|
+
}
|
|
2150
|
+
else
|
|
2151
|
+
first = divideForm(scale(d0, -1n), slope, 'exact');
|
|
2152
|
+
}
|
|
2153
|
+
else if (exit === 'ne') {
|
|
2154
|
+
if (lo0 > 0n || hi0 < 0n)
|
|
2155
|
+
first = num(0);
|
|
2156
|
+
else if (isNum(d0) && slope !== 0n)
|
|
2157
|
+
first = num(1);
|
|
2158
|
+
else
|
|
2159
|
+
return refuse('loop exit is not decided');
|
|
2160
|
+
}
|
|
2161
|
+
else {
|
|
2162
|
+
const sign = exit === 'ltu' || exit === 'leu' ? 1n : -1n;
|
|
2163
|
+
const strict = exit === 'ltu' || exit === 'gtu';
|
|
2164
|
+
const e0 = scale(d0, sign);
|
|
2165
|
+
const s = slope * sign;
|
|
2166
|
+
const [lo, hi] = span(e0, this.ranges);
|
|
2167
|
+
const holds = strict ? hi < 0n : hi <= 0n;
|
|
2168
|
+
const fails = strict ? lo >= 0n : lo > 0n;
|
|
2169
|
+
if (holds)
|
|
2170
|
+
first = num(0);
|
|
2171
|
+
else if (!fails || s >= 0n)
|
|
2172
|
+
return refuse('loop exit is not reached');
|
|
2173
|
+
else
|
|
2174
|
+
first = strict
|
|
2175
|
+
? cadd(divideForm(e0, -s, 'floor'), num(1))
|
|
2176
|
+
: divideForm(e0, -s, 'ceil');
|
|
2177
|
+
const at = (x) => {
|
|
2178
|
+
const m = new Map([['t', x]]);
|
|
2179
|
+
return [substCtl(a, m), substCtl(b, m)];
|
|
2180
|
+
};
|
|
2181
|
+
for (const x of [num(0), first])
|
|
2182
|
+
for (const value of at(x))
|
|
2183
|
+
if (!nowrap(value, this.ranges))
|
|
2184
|
+
return refuse('loop test values may wrap');
|
|
2185
|
+
}
|
|
2186
|
+
if (span(first, this.ranges)[0] < 0n)
|
|
2187
|
+
return refuse('loop exits before it starts');
|
|
2188
|
+
return first;
|
|
2189
|
+
}
|
|
2190
|
+
// #endregion
|
|
2191
|
+
// #region paths
|
|
2192
|
+
run(n, r) {
|
|
2193
|
+
this.paths++;
|
|
2194
|
+
const { layout, w } = this;
|
|
2195
|
+
const locals = this.types.map((type, j) => {
|
|
2196
|
+
if (j === layout.state)
|
|
2197
|
+
return { t: 'd', f: this.ring.state(w) };
|
|
2198
|
+
if (j === layout.ptr)
|
|
2199
|
+
return sym('P0');
|
|
2200
|
+
if (j === layout.len)
|
|
2201
|
+
return n !== undefined ? num(n) : cadd(scale(sym('Q'), BigInt(this.block)), num(r));
|
|
2202
|
+
if (type !== binaryen.i32 && type !== binaryen.i64)
|
|
2203
|
+
return undefined;
|
|
2204
|
+
return type === binaryen.i64 ? this.fromConst(64, 0n) : num(0);
|
|
2205
|
+
});
|
|
2206
|
+
this.ranges = new Map();
|
|
2207
|
+
if (n === undefined)
|
|
2208
|
+
this.ranges.set('Q', [1n, (M32 - BigInt(r)) / BigInt(this.block)]);
|
|
2209
|
+
this.st = {
|
|
2210
|
+
locals,
|
|
2211
|
+
base: sym('P0'),
|
|
2212
|
+
pending: 0,
|
|
2213
|
+
pre: undefined,
|
|
2214
|
+
mem: this.mem0.clone(),
|
|
2215
|
+
gen: undefined,
|
|
2216
|
+
written: []
|
|
2217
|
+
};
|
|
2218
|
+
let value;
|
|
2219
|
+
try {
|
|
2220
|
+
value = this.exec(this.body);
|
|
2221
|
+
}
|
|
2222
|
+
catch (error) {
|
|
2223
|
+
if (error instanceof Jump && error.label === RETURN)
|
|
2224
|
+
value = error.value;
|
|
2225
|
+
else if (error instanceof Jump)
|
|
2226
|
+
return refuse('branch to an unknown label');
|
|
2227
|
+
else if (error instanceof Undecided)
|
|
2228
|
+
return refuse('a branch is undecided');
|
|
2229
|
+
else
|
|
2230
|
+
throw error;
|
|
2231
|
+
}
|
|
2232
|
+
if (!value || value.t === 'p')
|
|
2233
|
+
return refuse('the function does not return a value');
|
|
2234
|
+
const result = value.t === 'd'
|
|
2235
|
+
? value.f
|
|
2236
|
+
: isNum(value) && w === 32
|
|
2237
|
+
? this.ring.konst(u32(value.c), 32)
|
|
2238
|
+
: refuse('the result is not data');
|
|
2239
|
+
if (result.w !== w)
|
|
2240
|
+
return refuse('result width differs from the state');
|
|
2241
|
+
for (const [address, byte] of this.st.mem.over) {
|
|
2242
|
+
const had = this.written.get(address);
|
|
2243
|
+
if (had !== undefined && had !== byte)
|
|
2244
|
+
refuse('paths initialize memory differently');
|
|
2245
|
+
this.written.set(address, byte);
|
|
2246
|
+
}
|
|
2247
|
+
return {
|
|
2248
|
+
result,
|
|
2249
|
+
pending: this.st.pending,
|
|
2250
|
+
base: this.st.base,
|
|
2251
|
+
mem: this.st.mem,
|
|
2252
|
+
written: this.st.written
|
|
2253
|
+
};
|
|
2254
|
+
}
|
|
2255
|
+
/**
|
|
2256
|
+
* Once the one byte call has written its byte, every call must write the bytes from the pointer
|
|
2257
|
+
* up to its length, each once. Each store was already compared with the transform of the byte.
|
|
2258
|
+
*/
|
|
2259
|
+
tile(written, length, first) {
|
|
2260
|
+
if (!written.length) {
|
|
2261
|
+
if (this.out1)
|
|
2262
|
+
refuse('the call stops writing the output');
|
|
2263
|
+
return;
|
|
2264
|
+
}
|
|
2265
|
+
let end = num(0);
|
|
2266
|
+
const rest = [...written];
|
|
2267
|
+
while (rest.length) {
|
|
2268
|
+
const i = rest.findIndex((w) => ceq(w.start, end));
|
|
2269
|
+
if (i < 0)
|
|
2270
|
+
return refuse('the bytes written do not follow one another from the pointer');
|
|
2271
|
+
const w = rest.splice(i, 1)[0];
|
|
2272
|
+
end = cadd(w.start, w.length);
|
|
2273
|
+
}
|
|
2274
|
+
if (!ceq(end, length))
|
|
2275
|
+
return refuse('the bytes written do not cover the input');
|
|
2276
|
+
if (first && !this.out1) {
|
|
2277
|
+
const form = written[0].form;
|
|
2278
|
+
if (!form || this.ring.positions(form).some((p) => p !== 0))
|
|
2279
|
+
return refuse('the output byte reads past its byte');
|
|
2280
|
+
this.out1 = form;
|
|
2281
|
+
}
|
|
2282
|
+
}
|
|
2283
|
+
check(n, r) {
|
|
2284
|
+
this.recording = n === 1 && this.out1 === undefined;
|
|
2285
|
+
const out = this.run(n, r);
|
|
2286
|
+
const ring = this.ring;
|
|
2287
|
+
if (opaque(ring, out.result))
|
|
2288
|
+
return refuse(`the state passes through an operation that is not affine: ${opaqueWhy}`);
|
|
2289
|
+
if (n === 0) {
|
|
2290
|
+
if (out.written.length)
|
|
2291
|
+
return refuse('a call over zero bytes writes memory');
|
|
2292
|
+
if (out.pending !== 0)
|
|
2293
|
+
return refuse('a zero length call reads input');
|
|
2294
|
+
this.zero = ring.equal(out.result, ring.state(this.w)) ? 'identity' : 'transforms';
|
|
2295
|
+
return;
|
|
2296
|
+
}
|
|
2297
|
+
const length = n !== undefined ? num(n) : cadd(scale(sym('Q'), BigInt(this.block)), num(r));
|
|
2298
|
+
const covered = cadd(out.base, num(out.pending));
|
|
2299
|
+
if (!ceq(covered, cadd(sym('P0'), length)))
|
|
2300
|
+
return refuse('folded bytes differ from the length');
|
|
2301
|
+
this.tile(out.written, length, n === 1);
|
|
2302
|
+
if (n === 1) {
|
|
2303
|
+
if (this.f1) {
|
|
2304
|
+
if (!ring.equal(out.result, this.f1))
|
|
2305
|
+
return refuse('byte step differs after initialization');
|
|
2306
|
+
return;
|
|
2307
|
+
}
|
|
2308
|
+
if (ring.positions(out.result).some((p) => p !== 0))
|
|
2309
|
+
return refuse('byte step reads past its byte');
|
|
2310
|
+
this.f1 = out.result;
|
|
2311
|
+
return;
|
|
2312
|
+
}
|
|
2313
|
+
let same = ring.equal(out.result, this.iterate(out.pending));
|
|
2314
|
+
if (!same && span(csub(out.base, sym('P0')), this.ranges)[0] >= 1n) {
|
|
2315
|
+
// the folded prefix is itself one byte step, so a state that was masked or normalized is already in range
|
|
2316
|
+
// the image byte sits above every input position and placeholder, so it cannot merge with a real byte
|
|
2317
|
+
const image = ring.subst(this.f1, ring.state(this.w), IMAGE);
|
|
2318
|
+
same = ring.equal(ring.subst(out.result, image, 0), ring.subst(this.iterate(out.pending), image, 0));
|
|
2319
|
+
}
|
|
2320
|
+
if (!same)
|
|
2321
|
+
return refuse(n !== undefined
|
|
2322
|
+
? `length ${n} is not the fold of the byte step`
|
|
2323
|
+
: `remainder ${r} is not the fold of the byte step`);
|
|
2324
|
+
}
|
|
2325
|
+
runAll() {
|
|
2326
|
+
this.check(1, 0);
|
|
2327
|
+
this.check(0, 0);
|
|
2328
|
+
for (let n = 2; n < this.block; n++)
|
|
2329
|
+
this.check(n, 0);
|
|
2330
|
+
for (let r = 0; r < this.block; r++)
|
|
2331
|
+
this.check(undefined, r);
|
|
2332
|
+
}
|
|
2333
|
+
}
|
|
2334
|
+
/**
|
|
2335
|
+
* `a & m` when every symbol coefficient is a multiple of 2^j: the low j bits come from the constant
|
|
2336
|
+
* alone, and the bits from j up are either all dropped or all kept by the mask.
|
|
2337
|
+
*/
|
|
2338
|
+
const maskControl = (a, m) => {
|
|
2339
|
+
if (m === M32)
|
|
2340
|
+
return a;
|
|
2341
|
+
if (m === 0n)
|
|
2342
|
+
return num(0);
|
|
2343
|
+
if (isNum(a))
|
|
2344
|
+
return num(u32(a.c) & m);
|
|
2345
|
+
let j = 32n;
|
|
2346
|
+
for (const v of a.s.values()) {
|
|
2347
|
+
const trailing = BigInt(v === 0n ? 32 : (v & -v).toString(2).length - 1);
|
|
2348
|
+
if (trailing < j)
|
|
2349
|
+
j = trailing;
|
|
2350
|
+
}
|
|
2351
|
+
if (j === 0n)
|
|
2352
|
+
return refuse('and of a value with low bits set');
|
|
2353
|
+
const unit = (1n << j) - 1n;
|
|
2354
|
+
const c = u32(a.c);
|
|
2355
|
+
if ((m & ~unit & M32) === 0n)
|
|
2356
|
+
return num(c & m);
|
|
2357
|
+
if ((m | unit) === M32)
|
|
2358
|
+
return norm((c & ~unit & M32) | (c & m & unit), a.s);
|
|
2359
|
+
return refuse('and with a mask that splits the symbolic bits');
|
|
2360
|
+
};
|
|
2361
|
+
// #endregion
|
|
2362
|
+
// #region certificates
|
|
2363
|
+
const compactImports = binaryen.Features.CompactImports;
|
|
2364
|
+
const merge = (ranges) => {
|
|
2365
|
+
const sorted = [...ranges].sort((a, b) => a[0] - b[0]);
|
|
2366
|
+
const out = [];
|
|
2367
|
+
for (const [start, end] of sorted) {
|
|
2368
|
+
const top = out[out.length - 1];
|
|
2369
|
+
if (top && start <= top[1])
|
|
2370
|
+
top[1] = Math.max(top[1], end);
|
|
2371
|
+
else
|
|
2372
|
+
out.push([start, end]);
|
|
2373
|
+
}
|
|
2374
|
+
return out;
|
|
2375
|
+
};
|
|
2376
|
+
const hex = (bytes) => bytes.map((b) => b.toString(16).padStart(2, '0')).join('');
|
|
2377
|
+
function certifyRing(ring, fn, layout, block, segments, limit, entry, moduleSha256) {
|
|
2378
|
+
const fresh = new Analysis(ring, fn, layout, block, new Mem(segments, limit), true);
|
|
2379
|
+
fresh.runAll();
|
|
2380
|
+
let final = fresh;
|
|
2381
|
+
if (fresh.written.size) {
|
|
2382
|
+
const warm = new Mem(segments, limit, new Map(fresh.written));
|
|
2383
|
+
final = new Analysis(ring, fn, layout, block, warm, false, fresh.f1, fresh.out1);
|
|
2384
|
+
final.runAll();
|
|
2385
|
+
}
|
|
2386
|
+
const f1 = fresh.f1;
|
|
2387
|
+
const step = ring.positions(f1).length === 0 ? ring.zeroStep(f1) : undefined;
|
|
2388
|
+
const operator = ring.operator(f1);
|
|
2389
|
+
const model = {
|
|
2390
|
+
kind: 'model',
|
|
2391
|
+
ring: ring.name,
|
|
2392
|
+
bits: layout.bits,
|
|
2393
|
+
align: 1,
|
|
2394
|
+
layout,
|
|
2395
|
+
operator,
|
|
2396
|
+
...(ring.modulus ? { modulus: ring.modulus(f1), digits: 2 } : {}),
|
|
2397
|
+
calls: 0,
|
|
2398
|
+
checks: []
|
|
2399
|
+
};
|
|
2400
|
+
const reads = merge(final.mem0.reads);
|
|
2401
|
+
const image = reads.map(([start, end]) => {
|
|
2402
|
+
const bytes = Array.from({ length: end - start }, (_, i) => final.mem0.byteAt(start + i));
|
|
2403
|
+
return {
|
|
2404
|
+
address: start,
|
|
2405
|
+
length: end - start,
|
|
2406
|
+
sha256: createHash('sha256').update(Uint8Array.from(bytes)).digest('hex')
|
|
2407
|
+
};
|
|
2408
|
+
});
|
|
2409
|
+
const addresses = [...fresh.written.keys()].sort((a, b) => a - b);
|
|
2410
|
+
const initialization = [];
|
|
2411
|
+
for (const address of addresses) {
|
|
2412
|
+
const top = initialization[initialization.length - 1];
|
|
2413
|
+
const byte = fresh.written.get(address);
|
|
2414
|
+
if (top && top.address + top.hex.length / 2 === address)
|
|
2415
|
+
top.hex += hex([byte]);
|
|
2416
|
+
else
|
|
2417
|
+
initialization.push({ address, hex: hex([byte]) });
|
|
2418
|
+
}
|
|
2419
|
+
const exclusions = merge([
|
|
2420
|
+
...reads,
|
|
2421
|
+
...fresh.mem0.reads,
|
|
2422
|
+
...initialization.map((w) => [w.address, w.address + w.hex.length / 2])
|
|
2423
|
+
]);
|
|
2424
|
+
return {
|
|
2425
|
+
kind: 'certificate',
|
|
2426
|
+
schema: 'folio.certificate.v1',
|
|
2427
|
+
checker: CHECKER,
|
|
2428
|
+
moduleSha256,
|
|
2429
|
+
entry,
|
|
2430
|
+
ring: ring.name,
|
|
2431
|
+
bits: layout.bits,
|
|
2432
|
+
block,
|
|
2433
|
+
layout,
|
|
2434
|
+
model,
|
|
2435
|
+
...(fresh.out1
|
|
2436
|
+
? { output: { inPlace: true, ...(step === undefined ? {} : { step }) } }
|
|
2437
|
+
: {}),
|
|
2438
|
+
zeroLength: fresh.zero,
|
|
2439
|
+
image,
|
|
2440
|
+
initialization,
|
|
2441
|
+
exclusions,
|
|
2442
|
+
stats: {
|
|
2443
|
+
paths: fresh.paths + (final === fresh ? 0 : final.paths),
|
|
2444
|
+
loops: fresh.loops + (final === fresh ? 0 : final.loops),
|
|
2445
|
+
expressions: fresh.expressions + (final === fresh ? 0 : final.expressions)
|
|
2446
|
+
}
|
|
2447
|
+
};
|
|
2448
|
+
}
|
|
2449
|
+
/**
|
|
2450
|
+
* Decides whether `entry(state, ptr, len)` in `bytes` is the byte fold of one affine step, for every
|
|
2451
|
+
* length of at least one byte. The proof runs the function symbolically: lengths below `block`
|
|
2452
|
+
* one by one, and every other length as `block * q + r` for each remainder r with `q` symbolic.
|
|
2453
|
+
* A loop whose trip count depends on `q` is summarized by induction over its iterations. The
|
|
2454
|
+
* checker either returns a certificate or the reason it could not prove the claim. Refusing says
|
|
2455
|
+
* nothing about the function, and an internal failure is also a refusal.
|
|
2456
|
+
*/
|
|
2457
|
+
export function certifyStream(bytes, entry, options = {}) {
|
|
2458
|
+
const blocks = options.block === undefined ? [4, 16] : [options.block];
|
|
2459
|
+
let result;
|
|
2460
|
+
const started = Date.now();
|
|
2461
|
+
for (const block of blocks) {
|
|
2462
|
+
result = certifyAt(bytes, entry, options, block, started);
|
|
2463
|
+
if (result.kind === 'certificate')
|
|
2464
|
+
break;
|
|
2465
|
+
}
|
|
2466
|
+
return result;
|
|
2467
|
+
}
|
|
2468
|
+
/** The number of memories a module declares, from its memory section. */
|
|
2469
|
+
function memoryCount(bytes) {
|
|
2470
|
+
let cursor = 8;
|
|
2471
|
+
const leb = () => {
|
|
2472
|
+
let value = 0;
|
|
2473
|
+
let shift = 0;
|
|
2474
|
+
let byte;
|
|
2475
|
+
do {
|
|
2476
|
+
byte = bytes[cursor++] ?? 0;
|
|
2477
|
+
value += (byte & 127) * 2 ** shift;
|
|
2478
|
+
shift += 7;
|
|
2479
|
+
} while (byte & 128 && cursor < bytes.length);
|
|
2480
|
+
return value;
|
|
2481
|
+
};
|
|
2482
|
+
while (cursor < bytes.length) {
|
|
2483
|
+
const id = bytes[cursor++];
|
|
2484
|
+
const length = leb();
|
|
2485
|
+
const end = cursor + length;
|
|
2486
|
+
if (id === 5)
|
|
2487
|
+
return leb();
|
|
2488
|
+
cursor = end;
|
|
2489
|
+
}
|
|
2490
|
+
return 0;
|
|
2491
|
+
}
|
|
2492
|
+
function certifyAt(bytes, entry, options, block, started) {
|
|
2493
|
+
resetAtoms();
|
|
2494
|
+
opaqueWhy = '';
|
|
2495
|
+
deadline = started + (options.maxMs ?? 30_000);
|
|
2496
|
+
const attempts = [];
|
|
2497
|
+
const fail = (reason) => ({ kind: 'refusal', reason, attempts });
|
|
2498
|
+
if (options.ring !== undefined && !['gf2', 'z2w', 'zp'].includes(options.ring))
|
|
2499
|
+
return fail('unknown ring');
|
|
2500
|
+
if (!Number.isSafeInteger(block) || block < 2 || block > 64 || (block & (block - 1)) !== 0)
|
|
2501
|
+
return fail('block must be a power of two from 2 to 64');
|
|
2502
|
+
let native;
|
|
2503
|
+
try {
|
|
2504
|
+
native = new WebAssembly.Module(Uint8Array.from(bytes));
|
|
2505
|
+
}
|
|
2506
|
+
catch {
|
|
2507
|
+
return fail('the bytes are not a valid module');
|
|
2508
|
+
}
|
|
2509
|
+
if (WebAssembly.Module.imports(native).length)
|
|
2510
|
+
return fail('the module has imports');
|
|
2511
|
+
if (memoryCount(bytes) > 1)
|
|
2512
|
+
return fail('the module has more than one memory');
|
|
2513
|
+
let module;
|
|
2514
|
+
try {
|
|
2515
|
+
module = binaryen.readBinary(bytes);
|
|
2516
|
+
}
|
|
2517
|
+
catch {
|
|
2518
|
+
return fail('the module cannot be read');
|
|
2519
|
+
}
|
|
2520
|
+
try {
|
|
2521
|
+
module.setFeatures(binaryen.Features.All & ~compactImports);
|
|
2522
|
+
if (module.getStart() !== 0)
|
|
2523
|
+
return fail('the module has a start function');
|
|
2524
|
+
const memory = module.getMemoryInfo();
|
|
2525
|
+
if (memory.shared || memory.is64)
|
|
2526
|
+
return fail('the memory is shared or 64-bit');
|
|
2527
|
+
const exported = module.getExport(entry);
|
|
2528
|
+
if (!exported)
|
|
2529
|
+
return fail(`no export named ${entry}`);
|
|
2530
|
+
const target = binaryen.getExportInfo(exported);
|
|
2531
|
+
if (target.kind !== binaryen.ExternalFunction)
|
|
2532
|
+
return fail(`${entry} is not a function`);
|
|
2533
|
+
const fn = binaryen.getFunctionInfo(module.getFunction(target.value));
|
|
2534
|
+
const params = binaryen.expandType(fn.params);
|
|
2535
|
+
const slot = options.layout ?? { state: 0, ptr: 1, len: 2 };
|
|
2536
|
+
if (params.length !== 3 || new Set([slot.state, slot.ptr, slot.len]).size !== 3)
|
|
2537
|
+
return fail('the entry takes other than three parameters');
|
|
2538
|
+
const stateType = params[slot.state];
|
|
2539
|
+
if (stateType !== binaryen.i32 && stateType !== binaryen.i64)
|
|
2540
|
+
return fail('the state is not an integer');
|
|
2541
|
+
if (fn.results !== stateType)
|
|
2542
|
+
return fail('the result type differs from the state type');
|
|
2543
|
+
if (params[slot.ptr] !== binaryen.i32 || params[slot.len] !== binaryen.i32)
|
|
2544
|
+
return fail('the pointer and length are not i32');
|
|
2545
|
+
const types = [...params, ...fn.vars];
|
|
2546
|
+
const layout = {
|
|
2547
|
+
entry,
|
|
2548
|
+
state: slot.state,
|
|
2549
|
+
ptr: slot.ptr,
|
|
2550
|
+
len: slot.len,
|
|
2551
|
+
bits: stateType === binaryen.i64 ? 64 : 32
|
|
2552
|
+
};
|
|
2553
|
+
const segments = [];
|
|
2554
|
+
const count = module.getNumDataSegments();
|
|
2555
|
+
for (let i = 0; i < count; i++) {
|
|
2556
|
+
let seg;
|
|
2557
|
+
try {
|
|
2558
|
+
seg = module.getDataSegmentInfo(module.getDataSegmentByIndex(i));
|
|
2559
|
+
}
|
|
2560
|
+
catch {
|
|
2561
|
+
return fail('a data segment offset is not a plain constant');
|
|
2562
|
+
}
|
|
2563
|
+
if (seg.passive)
|
|
2564
|
+
return fail('the module has a passive data segment');
|
|
2565
|
+
segments.push({ start: seg.offset, bytes: new Uint8Array(seg.data) });
|
|
2566
|
+
}
|
|
2567
|
+
const sha = createHash('sha256').update(bytes).digest('hex');
|
|
2568
|
+
for (const ring of options.ring ? [{ gf2, z2w, zp }[options.ring]] : [gf2, z2w, zp]) {
|
|
2569
|
+
try {
|
|
2570
|
+
return certifyRing(ring, {
|
|
2571
|
+
body: fn.body,
|
|
2572
|
+
types,
|
|
2573
|
+
callee: (name) => {
|
|
2574
|
+
const found = module.getFunction(name);
|
|
2575
|
+
if (!found)
|
|
2576
|
+
return undefined;
|
|
2577
|
+
const f = binaryen.getFunctionInfo(found);
|
|
2578
|
+
return {
|
|
2579
|
+
body: f.body,
|
|
2580
|
+
types: [...binaryen.expandType(f.params), ...f.vars]
|
|
2581
|
+
};
|
|
2582
|
+
}
|
|
2583
|
+
}, layout, block, segments, memory.initial * PAGE, entry, sha);
|
|
2584
|
+
}
|
|
2585
|
+
catch (error) {
|
|
2586
|
+
attempts.push({
|
|
2587
|
+
ring: ring.name,
|
|
2588
|
+
reason: error instanceof Refusal
|
|
2589
|
+
? error.message
|
|
2590
|
+
: `internal: ${error.message}`
|
|
2591
|
+
});
|
|
2592
|
+
}
|
|
2593
|
+
}
|
|
2594
|
+
return fail(attempts.map((a) => `${a.ring}: ${a.reason}`).join('; '));
|
|
2595
|
+
}
|
|
2596
|
+
finally {
|
|
2597
|
+
module.dispose();
|
|
2598
|
+
}
|
|
2599
|
+
}
|
|
2600
|
+
/** Re-derives the certificate from the module and compares everything except the work counters. */
|
|
2601
|
+
export function verifyCertificate(bytes, certificate) {
|
|
2602
|
+
if (certificate.checker !== CHECKER || certificate.schema !== 'folio.certificate.v1')
|
|
2603
|
+
return false;
|
|
2604
|
+
const again = certifyStream(bytes, certificate.entry, {
|
|
2605
|
+
layout: certificate.layout,
|
|
2606
|
+
block: certificate.block,
|
|
2607
|
+
ring: certificate.ring
|
|
2608
|
+
});
|
|
2609
|
+
if (again.kind !== 'certificate')
|
|
2610
|
+
return false;
|
|
2611
|
+
const strip = ({ stats: _stats, ...rest }) => JSON.stringify(rest, (_k, v) => (typeof v === 'bigint' ? v.toString() : v));
|
|
2612
|
+
return strip(again) === strip(certificate);
|
|
2613
|
+
}
|
|
2614
|
+
/** Whether `[ptr, ptr + len)` lies in memory and clear of every byte the proof depends on. */
|
|
2615
|
+
export function guardInput(certificate, memoryBytes, pointer, length) {
|
|
2616
|
+
if (!Number.isSafeInteger(memoryBytes) || memoryBytes < 0 || memoryBytes > 4294967296)
|
|
2617
|
+
return false;
|
|
2618
|
+
if (!Number.isSafeInteger(pointer) || !Number.isSafeInteger(length))
|
|
2619
|
+
return false;
|
|
2620
|
+
if (pointer < 0 || length < 0 || pointer > 4294967295)
|
|
2621
|
+
return false;
|
|
2622
|
+
const start = pointer;
|
|
2623
|
+
const end = start + length;
|
|
2624
|
+
if (end > memoryBytes)
|
|
2625
|
+
return false;
|
|
2626
|
+
return certificate.exclusions.every(([from, to]) => end <= from || start >= to);
|
|
2627
|
+
}
|
|
2628
|
+
// #endregion
|